├── .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 | |
|
|
14 |
15 | | Desktop | Web |
16 | | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
17 | |
|
|
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 | 
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 |
5 |
--------------------------------------------------------------------------------
/demoApp/composeApp/src/androidMain/res/xml/backup_rules.xml:
--------------------------------------------------------------------------------
1 |
8 |
9 |
13 |
--------------------------------------------------------------------------------
/demoApp/composeApp/src/androidMain/res/xml/data_extraction_rules.xml:
--------------------------------------------------------------------------------
1 |
6 |
7 |
8 |
12 |
13 |
19 |
--------------------------------------------------------------------------------
/demoApp/composeApp/src/commonMain/kotlin/sh/calvin/autolinktext/demo/App.kt:
--------------------------------------------------------------------------------
1 | package sh.calvin.autolinktext.demo
2 |
3 | import androidx.compose.foundation.layout.Arrangement
4 | import androidx.compose.foundation.layout.Column
5 | import androidx.compose.foundation.layout.fillMaxSize
6 | import androidx.compose.foundation.layout.padding
7 | import androidx.compose.foundation.layout.safeContentPadding
8 | import androidx.compose.foundation.rememberScrollState
9 | import androidx.compose.foundation.verticalScroll
10 | import androidx.compose.material3.MaterialTheme
11 | import androidx.compose.material3.Surface
12 | import androidx.compose.material3.Text
13 | import androidx.compose.runtime.Composable
14 | import androidx.compose.runtime.getValue
15 | import androidx.compose.runtime.mutableIntStateOf
16 | import androidx.compose.runtime.remember
17 | import androidx.compose.runtime.setValue
18 | import androidx.compose.ui.Alignment
19 | import androidx.compose.ui.Modifier
20 | import androidx.compose.ui.graphics.Color
21 | import androidx.compose.ui.text.AnnotatedString
22 | import androidx.compose.ui.text.SpanStyle
23 | import androidx.compose.ui.text.TextLinkStyles
24 | import androidx.compose.ui.text.font.FontWeight
25 | import androidx.compose.ui.text.style.TextDecoration
26 | import androidx.compose.ui.unit.dp
27 | import sh.calvin.autolinktext.SimpleTextMatchResult
28 | import sh.calvin.autolinktext.TextMatcher
29 | import sh.calvin.autolinktext.TextRule
30 | import sh.calvin.autolinktext.rememberAutoLinkText
31 | import sh.calvin.autolinktext.demo.ui.theme.AutoLinkTextTheme
32 | import sh.calvin.autolinktext.slice
33 |
34 | @Composable
35 | internal fun App() {
36 | AutoLinkTextTheme {
37 | MainScreen()
38 | }
39 | }
40 |
41 | @Composable
42 | fun MainScreen() {
43 | Surface(
44 | modifier = Modifier.fillMaxSize(),
45 | color = MaterialTheme.colorScheme.background
46 | ) {
47 | Column(
48 | modifier = Modifier
49 | .safeContentPadding()
50 | .verticalScroll(rememberScrollState())
51 | .padding(16.dp),
52 | horizontalAlignment = Alignment.CenterHorizontally,
53 | verticalArrangement = Arrangement.spacedBy(16.dp)
54 | ) {
55 | Text(
56 | AnnotatedString.rememberAutoLinkText(
57 | """
58 | |Visit https://www.google.com
59 | |Visit www.google.com
60 | |Email test@example.com
61 | |Call 6045557890
62 | |Call +1 (604) 555-7890
63 | |Call 604-555-7890
64 | """.trimMargin()
65 | )
66 | )
67 |
68 | Text(
69 | AnnotatedString.rememberAutoLinkText(
70 | "Visit https://www.google.com",
71 | defaultLinkStyles = TextLinkStyles(
72 | SpanStyle(
73 | color = Color.Blue,
74 | textDecoration = TextDecoration.Underline
75 | )
76 | )
77 | )
78 | )
79 |
80 | Text(
81 | AnnotatedString.rememberAutoLinkText(
82 | "Make your own rules like #hashtag and @mention",
83 | textRules = listOf(
84 | TextRule.Styleable(
85 | textMatcher = TextMatcher.StringMatcher("Make"),
86 | style = SpanStyle(fontWeight = FontWeight.Bold)
87 | ),
88 | TextRule.Clickable(
89 | textMatcher = TextMatcher.RegexMatcher(Regex("#\\w+")),
90 | onClick = {
91 | println("Hashtag ${it.matchedText} clicked")
92 | },
93 | ),
94 | TextRule.Url(
95 | textMatcher = TextMatcher.RegexMatcher(Regex("@\\w+")),
96 | styles = TextLinkStyles(
97 | SpanStyle(
98 | color = Color.Blue
99 | )
100 | ),
101 | urlProvider = { "https://twitter.com/${it.matchedText}" }
102 | )
103 | )
104 | )
105 | )
106 |
107 | Text(
108 | AnnotatedString.rememberAutoLinkText(
109 | "Style the same rule differently like #hashtag1 and #hashtag2",
110 | textRules = listOf(
111 | TextRule.Clickable(
112 | textMatcher = TextMatcher.RegexMatcher(Regex("#\\w+")),
113 | stylesProvider = {
114 | val hashtag = it.matchedText
115 | if (hashtag == "#hashtag1") {
116 | TextLinkStyles(
117 | SpanStyle(
118 | color = Color.Red,
119 | textDecoration = TextDecoration.Underline
120 | )
121 | )
122 | } else {
123 | TextLinkStyles(
124 | SpanStyle(
125 | color = Color.Blue,
126 | textDecoration = TextDecoration.Underline
127 | )
128 | )
129 | }
130 | },
131 | onClick = {
132 | println("Hashtag ${it.matchedText} clicked")
133 | },
134 | ),
135 | )
136 | )
137 | )
138 |
139 | Text(
140 | AnnotatedString.rememberAutoLinkText(
141 | "This is very important",
142 | textRules = listOf(
143 | TextRule.Styleable(
144 | textMatcher = TextMatcher.StringMatcher("important"),
145 | style = SpanStyle(color = Color.Red),
146 | )
147 | ),
148 | )
149 | )
150 |
151 | Text(
152 | AnnotatedString.rememberAutoLinkText(
153 | "Make every other word blue",
154 | textRules = listOf(
155 | TextRule.Styleable(
156 | textMatcher = TextMatcher.FunctionMatcher {
157 | val matches = mutableListOf>()
158 | var currentWordStart = 0
159 | "$it ".forEachIndexed { index, char ->
160 | if (char.isWhitespace()) {
161 | val match = SimpleTextMatchResult(
162 | start = currentWordStart,
163 | end = index,
164 | )
165 | if (it.slice(match).isNotBlank()) {
166 | matches.add(match)
167 | }
168 | currentWordStart = index + 1
169 | }
170 | }
171 | matches.filterIndexed { index, _ -> index % 2 == 0 }
172 | },
173 | style = SpanStyle(color = Color.Blue),
174 | ),
175 | ),
176 | )
177 | )
178 |
179 | var clickCount by remember { mutableIntStateOf(0) }
180 |
181 | Text(
182 | AnnotatedString.rememberAutoLinkText(
183 | "Make this clickable, this too but not THIS. Click count: $clickCount.",
184 | textRules = listOf(
185 | TextRule.Clickable(
186 | textMatcher = TextMatcher.StringMatcher("this"),
187 | onClick = {
188 | clickCount++
189 | },
190 | )
191 | )
192 | )
193 | )
194 | }
195 | }
196 | }
197 |
--------------------------------------------------------------------------------
/demoApp/composeApp/src/commonMain/kotlin/sh/calvin/autolinktext/demo/ui.theme/Color.kt:
--------------------------------------------------------------------------------
1 | package sh.calvin.autolinktext.demo.ui.theme
2 |
3 | import androidx.compose.ui.graphics.Color
4 |
5 | val Purple80 = Color(0xFFD0BCFF)
6 | val PurpleGrey80 = Color(0xFFCCC2DC)
7 | val Pink80 = Color(0xFFEFB8C8)
8 |
9 | val Purple40 = Color(0xFF6650a4)
10 | val PurpleGrey40 = Color(0xFF625b71)
11 | val Pink40 = Color(0xFF7D5260)
12 |
--------------------------------------------------------------------------------
/demoApp/composeApp/src/commonMain/kotlin/sh/calvin/autolinktext/demo/ui.theme/Theme.kt:
--------------------------------------------------------------------------------
1 | package sh.calvin.autolinktext.demo.ui.theme
2 |
3 | import androidx.compose.foundation.isSystemInDarkTheme
4 | import androidx.compose.material3.MaterialTheme
5 | import androidx.compose.material3.darkColorScheme
6 | import androidx.compose.material3.lightColorScheme
7 | import androidx.compose.runtime.Composable
8 |
9 | private val DarkColorScheme = darkColorScheme(
10 | primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80
11 | )
12 |
13 | private val LightColorScheme = lightColorScheme(
14 | primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40
15 |
16 | /* Other default colors to override
17 | background = Color(0xFFFFFBFE),
18 | surface = Color(0xFFFFFBFE),
19 | onPrimary = Color.White,
20 | onSecondary = Color.White,
21 | onTertiary = Color.White,
22 | onBackground = Color(0xFF1C1B1F),
23 | onSurface = Color(0xFF1C1B1F),
24 | */
25 | )
26 |
27 | @Composable
28 | fun AutoLinkTextTheme(
29 | darkTheme: Boolean = isSystemInDarkTheme(),
30 | content: @Composable () -> Unit,
31 | ) {
32 | val colorScheme = when {
33 | darkTheme -> DarkColorScheme
34 | else -> LightColorScheme
35 | }
36 | MaterialTheme(
37 | colorScheme = colorScheme, typography = Typography, content = content
38 | )
39 | }
40 |
--------------------------------------------------------------------------------
/demoApp/composeApp/src/commonMain/kotlin/sh/calvin/autolinktext/demo/ui.theme/Type.kt:
--------------------------------------------------------------------------------
1 | package sh.calvin.autolinktext.demo.ui.theme
2 |
3 | import androidx.compose.material3.Typography
4 | import androidx.compose.ui.text.TextStyle
5 | import androidx.compose.ui.text.font.FontFamily
6 | import androidx.compose.ui.text.font.FontWeight
7 | import androidx.compose.ui.unit.sp
8 |
9 | // Set of Material typography styles to start with
10 | val Typography = Typography(
11 | bodyLarge = TextStyle(
12 | fontFamily = FontFamily.Default,
13 | fontWeight = FontWeight.Normal,
14 | fontSize = 16.sp,
15 | lineHeight = 24.sp,
16 | letterSpacing = 0.5.sp
17 | )
18 | /* Other default text styles to override
19 | titleLarge = TextStyle(
20 | fontFamily = FontFamily.Default,
21 | fontWeight = FontWeight.Normal,
22 | fontSize = 22.sp,
23 | lineHeight = 28.sp,
24 | letterSpacing = 0.sp
25 | ),
26 | labelSmall = TextStyle(
27 | fontFamily = FontFamily.Default,
28 | fontWeight = FontWeight.Medium,
29 | fontSize = 11.sp,
30 | lineHeight = 16.sp,
31 | letterSpacing = 0.5.sp
32 | )
33 | */
34 | )
35 |
--------------------------------------------------------------------------------
/demoApp/composeApp/src/iosMain/kotlin/main.kt:
--------------------------------------------------------------------------------
1 | import androidx.compose.ui.window.ComposeUIViewController
2 | import platform.UIKit.UIViewController
3 | import sh.calvin.autolinktext.demo.App
4 |
5 | fun MainViewController(): UIViewController = ComposeUIViewController { App() }
6 |
--------------------------------------------------------------------------------
/demoApp/composeApp/src/jsMain/kotlin/main.kt:
--------------------------------------------------------------------------------
1 | import androidx.compose.ui.ExperimentalComposeUiApi
2 | import androidx.compose.ui.window.CanvasBasedWindow
3 | import org.jetbrains.skiko.wasm.onWasmReady
4 | import sh.calvin.autolinktext.demo.App
5 |
6 | @OptIn(ExperimentalComposeUiApi::class)
7 | fun main() {
8 | onWasmReady {
9 | CanvasBasedWindow(canvasElementId = "ComposeTarget") {
10 | App()
11 | }
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/demoApp/composeApp/src/jsMain/resources/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Compose App
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/demoApp/composeApp/src/jvmMain/kotlin/main.kt:
--------------------------------------------------------------------------------
1 | import androidx.compose.ui.unit.dp
2 | import androidx.compose.ui.window.Window
3 | import androidx.compose.ui.window.application
4 | import androidx.compose.ui.window.rememberWindowState
5 | import sh.calvin.autolinktext.demo.App
6 | import java.awt.Dimension
7 |
8 | fun main() = application {
9 | Window(
10 | title = "AutoLinkText",
11 | state = rememberWindowState(width = 600.dp, height = 800.dp),
12 | onCloseRequest = ::exitApplication,
13 | ) {
14 | window.minimumSize = Dimension(350, 600)
15 | App()
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/demoApp/composeApp/src/wasmJsMain/kotlin/main.kt:
--------------------------------------------------------------------------------
1 | import androidx.compose.ui.ExperimentalComposeUiApi
2 | import androidx.compose.ui.window.CanvasBasedWindow
3 | import sh.calvin.autolinktext.demo.App
4 |
5 | @OptIn(ExperimentalComposeUiApi::class)
6 | fun main() {
7 | CanvasBasedWindow(canvasElementId = "ComposeTarget") {
8 | App()
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/demoApp/composeApp/src/wasmJsMain/resources/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Compose App
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/demoApp/iosApp/iosApp.xcodeproj/project.pbxproj:
--------------------------------------------------------------------------------
1 | // !$*UTF8*$!
2 | {
3 | archiveVersion = 1;
4 | classes = {
5 | };
6 | objectVersion = 56;
7 | objects = {
8 |
9 | /* Begin PBXBuildFile section */
10 | A93A953B29CC810C00F8E227 /* iosApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = A93A953A29CC810C00F8E227 /* iosApp.swift */; };
11 | A93A953F29CC810D00F8E227 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = A93A953E29CC810D00F8E227 /* Assets.xcassets */; };
12 | A93A954229CC810D00F8E227 /* Preview Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = A93A954129CC810D00F8E227 /* Preview Assets.xcassets */; };
13 | /* End PBXBuildFile section */
14 |
15 | /* Begin PBXFileReference section */
16 | 3EAD05542D0FD25100F37B6E /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = Info.plist; sourceTree = ""; };
17 | A93A953729CC810C00F8E227 /* AutoLinkText.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = AutoLinkText.app; sourceTree = BUILT_PRODUCTS_DIR; };
18 | A93A953A29CC810C00F8E227 /* iosApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = iosApp.swift; sourceTree = ""; };
19 | A93A953E29CC810D00F8E227 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; };
20 | A93A954129CC810D00F8E227 /* Preview Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = "Preview Assets.xcassets"; sourceTree = ""; };
21 | /* End PBXFileReference section */
22 |
23 | /* Begin PBXFrameworksBuildPhase section */
24 | A93A953429CC810C00F8E227 /* Frameworks */ = {
25 | isa = PBXFrameworksBuildPhase;
26 | buildActionMask = 2147483647;
27 | files = (
28 | );
29 | runOnlyForDeploymentPostprocessing = 0;
30 | };
31 | /* End PBXFrameworksBuildPhase section */
32 |
33 | /* Begin PBXGroup section */
34 | A93A952E29CC810C00F8E227 = {
35 | isa = PBXGroup;
36 | children = (
37 | A93A953929CC810C00F8E227 /* iosApp */,
38 | A93A953829CC810C00F8E227 /* Products */,
39 | C4127409AE3703430489E7BC /* Frameworks */,
40 | );
41 | sourceTree = "";
42 | };
43 | A93A953829CC810C00F8E227 /* Products */ = {
44 | isa = PBXGroup;
45 | children = (
46 | A93A953729CC810C00F8E227 /* AutoLinkText.app */,
47 | );
48 | name = Products;
49 | sourceTree = "";
50 | };
51 | A93A953929CC810C00F8E227 /* iosApp */ = {
52 | isa = PBXGroup;
53 | children = (
54 | 3EAD05542D0FD25100F37B6E /* Info.plist */,
55 | A93A953A29CC810C00F8E227 /* iosApp.swift */,
56 | A93A953E29CC810D00F8E227 /* Assets.xcassets */,
57 | A93A954029CC810D00F8E227 /* Preview Content */,
58 | );
59 | path = iosApp;
60 | sourceTree = "";
61 | };
62 | A93A954029CC810D00F8E227 /* Preview Content */ = {
63 | isa = PBXGroup;
64 | children = (
65 | A93A954129CC810D00F8E227 /* Preview Assets.xcassets */,
66 | );
67 | path = "Preview Content";
68 | sourceTree = "";
69 | };
70 | C4127409AE3703430489E7BC /* Frameworks */ = {
71 | isa = PBXGroup;
72 | children = (
73 | );
74 | name = Frameworks;
75 | sourceTree = "";
76 | };
77 | /* End PBXGroup section */
78 |
79 | /* Begin PBXNativeTarget section */
80 | A93A953629CC810C00F8E227 /* iosApp */ = {
81 | isa = PBXNativeTarget;
82 | buildConfigurationList = A93A954529CC810D00F8E227 /* Build configuration list for PBXNativeTarget "iosApp" */;
83 | buildPhases = (
84 | A9D80A052AAB5CDE006C8738 /* ShellScript */,
85 | A93A953329CC810C00F8E227 /* Sources */,
86 | A93A953429CC810C00F8E227 /* Frameworks */,
87 | A93A953529CC810C00F8E227 /* Resources */,
88 | );
89 | buildRules = (
90 | );
91 | dependencies = (
92 | );
93 | name = iosApp;
94 | productName = iosApp;
95 | productReference = A93A953729CC810C00F8E227 /* AutoLinkText.app */;
96 | productType = "com.apple.product-type.application";
97 | };
98 | /* End PBXNativeTarget section */
99 |
100 | /* Begin PBXProject section */
101 | A93A952F29CC810C00F8E227 /* Project object */ = {
102 | isa = PBXProject;
103 | attributes = {
104 | LastSwiftUpdateCheck = 1420;
105 | LastUpgradeCheck = 1420;
106 | TargetAttributes = {
107 | A93A953629CC810C00F8E227 = {
108 | CreatedOnToolsVersion = 14.2;
109 | };
110 | };
111 | };
112 | buildConfigurationList = A93A953229CC810C00F8E227 /* Build configuration list for PBXProject "iosApp" */;
113 | compatibilityVersion = "Xcode 14.0";
114 | developmentRegion = en;
115 | hasScannedForEncodings = 0;
116 | knownRegions = (
117 | en,
118 | Base,
119 | );
120 | mainGroup = A93A952E29CC810C00F8E227;
121 | productRefGroup = A93A953829CC810C00F8E227 /* Products */;
122 | projectDirPath = "";
123 | projectRoot = "";
124 | targets = (
125 | A93A953629CC810C00F8E227 /* iosApp */,
126 | );
127 | };
128 | /* End PBXProject section */
129 |
130 | /* Begin PBXResourcesBuildPhase section */
131 | A93A953529CC810C00F8E227 /* Resources */ = {
132 | isa = PBXResourcesBuildPhase;
133 | buildActionMask = 2147483647;
134 | files = (
135 | A93A954229CC810D00F8E227 /* Preview Assets.xcassets in Resources */,
136 | A93A953F29CC810D00F8E227 /* Assets.xcassets in Resources */,
137 | );
138 | runOnlyForDeploymentPostprocessing = 0;
139 | };
140 | /* End PBXResourcesBuildPhase section */
141 |
142 | /* Begin PBXShellScriptBuildPhase section */
143 | A9D80A052AAB5CDE006C8738 /* ShellScript */ = {
144 | isa = PBXShellScriptBuildPhase;
145 | buildActionMask = 2147483647;
146 | files = (
147 | );
148 | inputFileListPaths = (
149 | );
150 | inputPaths = (
151 | );
152 | outputFileListPaths = (
153 | );
154 | outputPaths = (
155 | );
156 | runOnlyForDeploymentPostprocessing = 0;
157 | shellPath = /bin/sh;
158 | shellScript = "cd \"$SRCROOT/../..\"\n./gradlew :demoApp:composeApp:embedAndSignAppleFrameworkForXcode\n";
159 | };
160 | /* End PBXShellScriptBuildPhase section */
161 |
162 | /* Begin PBXSourcesBuildPhase section */
163 | A93A953329CC810C00F8E227 /* Sources */ = {
164 | isa = PBXSourcesBuildPhase;
165 | buildActionMask = 2147483647;
166 | files = (
167 | A93A953B29CC810C00F8E227 /* iosApp.swift in Sources */,
168 | );
169 | runOnlyForDeploymentPostprocessing = 0;
170 | };
171 | /* End PBXSourcesBuildPhase section */
172 |
173 | /* Begin XCBuildConfiguration section */
174 | A93A954329CC810D00F8E227 /* Debug */ = {
175 | isa = XCBuildConfiguration;
176 | buildSettings = {
177 | ALWAYS_SEARCH_USER_PATHS = NO;
178 | CLANG_ANALYZER_NONNULL = YES;
179 | CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
180 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
181 | CLANG_ENABLE_MODULES = YES;
182 | CLANG_ENABLE_OBJC_ARC = YES;
183 | CLANG_ENABLE_OBJC_WEAK = YES;
184 | CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
185 | CLANG_WARN_BOOL_CONVERSION = YES;
186 | CLANG_WARN_COMMA = YES;
187 | CLANG_WARN_CONSTANT_CONVERSION = YES;
188 | CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
189 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
190 | CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
191 | CLANG_WARN_EMPTY_BODY = YES;
192 | CLANG_WARN_ENUM_CONVERSION = YES;
193 | CLANG_WARN_INFINITE_RECURSION = YES;
194 | CLANG_WARN_INT_CONVERSION = YES;
195 | CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
196 | CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
197 | CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
198 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
199 | CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
200 | CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
201 | CLANG_WARN_STRICT_PROTOTYPES = YES;
202 | CLANG_WARN_SUSPICIOUS_MOVE = YES;
203 | CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
204 | CLANG_WARN_UNREACHABLE_CODE = YES;
205 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
206 | COPY_PHASE_STRIP = NO;
207 | DEBUG_INFORMATION_FORMAT = dwarf;
208 | ENABLE_STRICT_OBJC_MSGSEND = YES;
209 | ENABLE_TESTABILITY = YES;
210 | GCC_C_LANGUAGE_STANDARD = gnu11;
211 | GCC_DYNAMIC_NO_PIC = NO;
212 | GCC_NO_COMMON_BLOCKS = YES;
213 | GCC_OPTIMIZATION_LEVEL = 0;
214 | GCC_PREPROCESSOR_DEFINITIONS = (
215 | "DEBUG=1",
216 | "$(inherited)",
217 | );
218 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
219 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
220 | GCC_WARN_UNDECLARED_SELECTOR = YES;
221 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
222 | GCC_WARN_UNUSED_FUNCTION = YES;
223 | GCC_WARN_UNUSED_VARIABLE = YES;
224 | IPHONEOS_DEPLOYMENT_TARGET = 16.2;
225 | MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
226 | MTL_FAST_MATH = YES;
227 | ONLY_ACTIVE_ARCH = YES;
228 | SDKROOT = iphoneos;
229 | SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
230 | SWIFT_OPTIMIZATION_LEVEL = "-Onone";
231 | };
232 | name = Debug;
233 | };
234 | A93A954429CC810D00F8E227 /* Release */ = {
235 | isa = XCBuildConfiguration;
236 | buildSettings = {
237 | ALWAYS_SEARCH_USER_PATHS = NO;
238 | CLANG_ANALYZER_NONNULL = YES;
239 | CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
240 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
241 | CLANG_ENABLE_MODULES = YES;
242 | CLANG_ENABLE_OBJC_ARC = YES;
243 | CLANG_ENABLE_OBJC_WEAK = YES;
244 | CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
245 | CLANG_WARN_BOOL_CONVERSION = YES;
246 | CLANG_WARN_COMMA = YES;
247 | CLANG_WARN_CONSTANT_CONVERSION = YES;
248 | CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
249 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
250 | CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
251 | CLANG_WARN_EMPTY_BODY = YES;
252 | CLANG_WARN_ENUM_CONVERSION = YES;
253 | CLANG_WARN_INFINITE_RECURSION = YES;
254 | CLANG_WARN_INT_CONVERSION = YES;
255 | CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
256 | CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
257 | CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
258 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
259 | CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
260 | CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
261 | CLANG_WARN_STRICT_PROTOTYPES = YES;
262 | CLANG_WARN_SUSPICIOUS_MOVE = YES;
263 | CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
264 | CLANG_WARN_UNREACHABLE_CODE = YES;
265 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
266 | COPY_PHASE_STRIP = NO;
267 | DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
268 | ENABLE_NS_ASSERTIONS = NO;
269 | ENABLE_STRICT_OBJC_MSGSEND = YES;
270 | GCC_C_LANGUAGE_STANDARD = gnu11;
271 | GCC_NO_COMMON_BLOCKS = YES;
272 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
273 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
274 | GCC_WARN_UNDECLARED_SELECTOR = YES;
275 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
276 | GCC_WARN_UNUSED_FUNCTION = YES;
277 | GCC_WARN_UNUSED_VARIABLE = YES;
278 | IPHONEOS_DEPLOYMENT_TARGET = 16.2;
279 | MTL_ENABLE_DEBUG_INFO = NO;
280 | MTL_FAST_MATH = YES;
281 | SDKROOT = iphoneos;
282 | SWIFT_COMPILATION_MODE = wholemodule;
283 | SWIFT_OPTIMIZATION_LEVEL = "-O";
284 | VALIDATE_PRODUCT = YES;
285 | };
286 | name = Release;
287 | };
288 | A93A954629CC810D00F8E227 /* Debug */ = {
289 | isa = XCBuildConfiguration;
290 | buildSettings = {
291 | ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
292 | ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
293 | CODE_SIGN_STYLE = Automatic;
294 | CURRENT_PROJECT_VERSION = 1;
295 | DEVELOPMENT_ASSET_PATHS = "\"iosApp/Preview Content\"";
296 | DEVELOPMENT_TEAM = 5G4K3V6DDY;
297 | ENABLE_PREVIEWS = YES;
298 | FRAMEWORK_SEARCH_PATHS = (
299 | "${inherited}",
300 | "$(SRCROOT)/../composeApp/build/xcode-frameworks/$(CONFIGURATION)/$(SDK_NAME)",
301 | );
302 | GENERATE_INFOPLIST_FILE = YES;
303 | INFOPLIST_FILE = iosApp/Info.plist;
304 | INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES;
305 | INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES;
306 | INFOPLIST_KEY_UILaunchScreen_Generation = YES;
307 | INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
308 | INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
309 | LD_RUNPATH_SEARCH_PATHS = (
310 | "$(inherited)",
311 | "@executable_path/Frameworks",
312 | );
313 | MARKETING_VERSION = 1.0;
314 | OTHER_LDFLAGS = (
315 | "${inherited}",
316 | "-framework",
317 | ComposeApp,
318 | );
319 | PRODUCT_BUNDLE_IDENTIFIER = sh.calvin.autolinktext.demo.iosApp;
320 | PRODUCT_NAME = AutoLinkText;
321 | SWIFT_EMIT_LOC_STRINGS = YES;
322 | SWIFT_VERSION = 5.0;
323 | TARGETED_DEVICE_FAMILY = "1,2";
324 | };
325 | name = Debug;
326 | };
327 | A93A954729CC810D00F8E227 /* Release */ = {
328 | isa = XCBuildConfiguration;
329 | buildSettings = {
330 | ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
331 | ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
332 | CODE_SIGN_STYLE = Automatic;
333 | CURRENT_PROJECT_VERSION = 1;
334 | DEVELOPMENT_ASSET_PATHS = "\"iosApp/Preview Content\"";
335 | DEVELOPMENT_TEAM = 5G4K3V6DDY;
336 | ENABLE_PREVIEWS = YES;
337 | FRAMEWORK_SEARCH_PATHS = (
338 | "${inherited}",
339 | "$(SRCROOT)/../composeApp/build/xcode-frameworks/$(CONFIGURATION)/$(SDK_NAME)",
340 | );
341 | GENERATE_INFOPLIST_FILE = YES;
342 | INFOPLIST_FILE = iosApp/Info.plist;
343 | INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES;
344 | INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES;
345 | INFOPLIST_KEY_UILaunchScreen_Generation = YES;
346 | INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
347 | INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
348 | LD_RUNPATH_SEARCH_PATHS = (
349 | "$(inherited)",
350 | "@executable_path/Frameworks",
351 | );
352 | MARKETING_VERSION = 1.0;
353 | OTHER_LDFLAGS = (
354 | "${inherited}",
355 | "-framework",
356 | ComposeApp,
357 | );
358 | PRODUCT_BUNDLE_IDENTIFIER = sh.calvin.autolinktext.demo.iosApp;
359 | PRODUCT_NAME = AutoLinkText;
360 | SWIFT_EMIT_LOC_STRINGS = YES;
361 | SWIFT_VERSION = 5.0;
362 | TARGETED_DEVICE_FAMILY = "1,2";
363 | };
364 | name = Release;
365 | };
366 | /* End XCBuildConfiguration section */
367 |
368 | /* Begin XCConfigurationList section */
369 | A93A953229CC810C00F8E227 /* Build configuration list for PBXProject "iosApp" */ = {
370 | isa = XCConfigurationList;
371 | buildConfigurations = (
372 | A93A954329CC810D00F8E227 /* Debug */,
373 | A93A954429CC810D00F8E227 /* Release */,
374 | );
375 | defaultConfigurationIsVisible = 0;
376 | defaultConfigurationName = Release;
377 | };
378 | A93A954529CC810D00F8E227 /* Build configuration list for PBXNativeTarget "iosApp" */ = {
379 | isa = XCConfigurationList;
380 | buildConfigurations = (
381 | A93A954629CC810D00F8E227 /* Debug */,
382 | A93A954729CC810D00F8E227 /* Release */,
383 | );
384 | defaultConfigurationIsVisible = 0;
385 | defaultConfigurationName = Release;
386 | };
387 | /* End XCConfigurationList section */
388 | };
389 | rootObject = A93A952F29CC810C00F8E227 /* Project object */;
390 | }
391 |
--------------------------------------------------------------------------------
/demoApp/iosApp/iosApp.xcodeproj/project.xcworkspace/contents.xcworkspacedata:
--------------------------------------------------------------------------------
1 |
2 |
4 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/demoApp/iosApp/iosApp.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | IDEDidComputeMac32BitWarning
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/demoApp/iosApp/iosApp/Assets.xcassets/AccentColor.colorset/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "colors" : [
3 | {
4 | "idiom" : "universal"
5 | }
6 | ],
7 | "info" : {
8 | "author" : "xcode",
9 | "version" : 1
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/demoApp/iosApp/iosApp/Assets.xcassets/AppIcon.appiconset/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "images" : [
3 | {
4 | "idiom" : "universal",
5 | "platform" : "ios",
6 | "size" : "1024x1024"
7 | }
8 | ],
9 | "info" : {
10 | "author" : "xcode",
11 | "version" : 1
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/demoApp/iosApp/iosApp/Assets.xcassets/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "info" : {
3 | "author" : "xcode",
4 | "version" : 1
5 | }
6 | }
7 |
--------------------------------------------------------------------------------
/demoApp/iosApp/iosApp/Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | CADisableMinimumFrameDurationOnPhone
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/demoApp/iosApp/iosApp/Preview Content/Preview Assets.xcassets/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "info" : {
3 | "author" : "xcode",
4 | "version" : 1
5 | }
6 | }
7 |
--------------------------------------------------------------------------------
/demoApp/iosApp/iosApp/iosApp.swift:
--------------------------------------------------------------------------------
1 | import UIKit
2 | import SwiftUI
3 | import ComposeApp
4 |
5 | @main
6 | struct iosApp: App {
7 | var body: some Scene {
8 | WindowGroup {
9 | ContentView()
10 | }
11 | }
12 | }
13 |
14 | struct ContentView: View {
15 | var body: some View {
16 | ComposeView().ignoresSafeArea()
17 | }
18 | }
19 |
20 | struct ComposeView: UIViewControllerRepresentable {
21 | func makeUIViewController(context: Context) -> UIViewController {
22 | MainKt.MainViewController()
23 | }
24 |
25 | func updateUIViewController(_ uiViewController: UIViewController, context: Context) {}
26 | }
27 |
--------------------------------------------------------------------------------
/demoApp/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | #Gradle
2 | org.gradle.jvmargs=-Xmx2048M -Dfile.encoding=UTF-8 -Dkotlin.daemon.jvm.options\="-Xmx2048M"
3 | org.gradle.caching=true
4 | #org.gradle.configuration-cache=true
5 |
6 | #Kotlin
7 | kotlin.code.style=official
8 |
9 | #Android
10 | android.useAndroidX=true
11 | android.nonTransitiveRClass=true
12 |
13 | # https://vanniktech.github.io/gradle-maven-publish-plugin/central/#configuring-maven-central
14 | SONATYPE_HOST=S01
15 | RELEASE_SIGNING_ENABLED=true
16 |
17 | org.jetbrains.compose.experimental.wasm.enabled=true
18 | org.jetbrains.compose.experimental.jscanvas.enabled=true
19 |
--------------------------------------------------------------------------------
/gradle/libs.versions.toml:
--------------------------------------------------------------------------------
1 | [versions]
2 | agp = "8.8.2"
3 | kermit = "2.0.3"
4 | kotlin = "2.0.21"
5 | compose = "1.7.0"
6 | androidxCore = "1.15.0"
7 | activityCompose = "1.9.3"
8 | mavenPublish = "0.27.0"
9 | libphonenumber = "8.13.31"
10 | robolectric = "4.14.1"
11 |
12 | [libraries]
13 | kermit = { module = "co.touchlab:kermit", version.ref = "kermit" }
14 | kotlin-test = { module = "org.jetbrains.kotlin:kotlin-test", version.ref = "kotlin" }
15 | androidx-core-ktx = { module = "androidx.core:core-ktx", version.ref = "androidxCore" }
16 | androidx-activity-compose = { module = "androidx.activity:activity-compose", version.ref = "activityCompose" }
17 | libphonenumber = { group = "com.googlecode.libphonenumber", name = "libphonenumber", version.ref = "libphonenumber" }
18 | robolectric = { module = "org.robolectric:robolectric", version.ref = "robolectric" }
19 |
20 | [plugins]
21 | android-application = { id = "com.android.application", version.ref = "agp" }
22 | android-library = { id = "com.android.library", version.ref = "agp" }
23 | compose = { id = "org.jetbrains.compose", version.ref = "compose" }
24 | kotlin-multiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" }
25 | compose-compiler = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
26 | maven-publish = { id = "com.vanniktech.maven.publish", version.ref = "mavenPublish" }
27 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Calvin-LL/AutoLinkText/d59e9146208423fec3778b57503240d71d46df67/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Mon Mar 04 00:04:53 PST 2024
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-bin.zip
5 | zipStoreBase=GRADLE_USER_HOME
6 | zipStorePath=wrapper/dists
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | #
4 | # Copyright 2015 the original author or authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | ##
21 | ## Gradle start up script for UN*X
22 | ##
23 | ##############################################################################
24 |
25 | # Attempt to set APP_HOME
26 | # Resolve links: $0 may be a link
27 | PRG="$0"
28 | # Need this for relative symlinks.
29 | while [ -h "$PRG" ] ; do
30 | ls=`ls -ld "$PRG"`
31 | link=`expr "$ls" : '.*-> \(.*\)$'`
32 | if expr "$link" : '/.*' > /dev/null; then
33 | PRG="$link"
34 | else
35 | PRG=`dirname "$PRG"`"/$link"
36 | fi
37 | done
38 | SAVED="`pwd`"
39 | cd "`dirname \"$PRG\"`/" >/dev/null
40 | APP_HOME="`pwd -P`"
41 | cd "$SAVED" >/dev/null
42 |
43 | APP_NAME="Gradle"
44 | APP_BASE_NAME=`basename "$0"`
45 |
46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
48 |
49 | # Use the maximum available, or set MAX_FD != -1 to use that value.
50 | MAX_FD="maximum"
51 |
52 | warn () {
53 | echo "$*"
54 | }
55 |
56 | die () {
57 | echo
58 | echo "$*"
59 | echo
60 | exit 1
61 | }
62 |
63 | # OS specific support (must be 'true' or 'false').
64 | cygwin=false
65 | msys=false
66 | darwin=false
67 | nonstop=false
68 | case "`uname`" in
69 | CYGWIN* )
70 | cygwin=true
71 | ;;
72 | Darwin* )
73 | darwin=true
74 | ;;
75 | MINGW* )
76 | msys=true
77 | ;;
78 | NONSTOP* )
79 | nonstop=true
80 | ;;
81 | esac
82 |
83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
84 |
85 |
86 | # Determine the Java command to use to start the JVM.
87 | if [ -n "$JAVA_HOME" ] ; then
88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
89 | # IBM's JDK on AIX uses strange locations for the executables
90 | JAVACMD="$JAVA_HOME/jre/sh/java"
91 | else
92 | JAVACMD="$JAVA_HOME/bin/java"
93 | fi
94 | if [ ! -x "$JAVACMD" ] ; then
95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
96 |
97 | Please set the JAVA_HOME variable in your environment to match the
98 | location of your Java installation."
99 | fi
100 | else
101 | JAVACMD="java"
102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
103 |
104 | Please set the JAVA_HOME variable in your environment to match the
105 | location of your Java installation."
106 | fi
107 |
108 | # Increase the maximum file descriptors if we can.
109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
110 | MAX_FD_LIMIT=`ulimit -H -n`
111 | if [ $? -eq 0 ] ; then
112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
113 | MAX_FD="$MAX_FD_LIMIT"
114 | fi
115 | ulimit -n $MAX_FD
116 | if [ $? -ne 0 ] ; then
117 | warn "Could not set maximum file descriptor limit: $MAX_FD"
118 | fi
119 | else
120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
121 | fi
122 | fi
123 |
124 | # For Darwin, add options to specify how the application appears in the dock
125 | if $darwin; then
126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
127 | fi
128 |
129 | # For Cygwin or MSYS, switch paths to Windows format before running java
130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
133 |
134 | JAVACMD=`cygpath --unix "$JAVACMD"`
135 |
136 | # We build the pattern for arguments to be converted via cygpath
137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
138 | SEP=""
139 | for dir in $ROOTDIRSRAW ; do
140 | ROOTDIRS="$ROOTDIRS$SEP$dir"
141 | SEP="|"
142 | done
143 | OURCYGPATTERN="(^($ROOTDIRS))"
144 | # Add a user-defined pattern to the cygpath arguments
145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
147 | fi
148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
149 | i=0
150 | for arg in "$@" ; do
151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
153 |
154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
156 | else
157 | eval `echo args$i`="\"$arg\""
158 | fi
159 | i=`expr $i + 1`
160 | done
161 | case $i in
162 | 0) set -- ;;
163 | 1) set -- "$args0" ;;
164 | 2) set -- "$args0" "$args1" ;;
165 | 3) set -- "$args0" "$args1" "$args2" ;;
166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;;
167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
172 | esac
173 | fi
174 |
175 | # Escape application args
176 | save () {
177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
178 | echo " "
179 | }
180 | APP_ARGS=`save "$@"`
181 |
182 | # Collect all arguments for the java command, following the shell quoting and substitution rules
183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
184 |
185 | exec "$JAVACMD" "$@"
186 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
34 |
35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
37 |
38 | @rem Find java.exe
39 | if defined JAVA_HOME goto findJavaFromJavaHome
40 |
41 | set JAVA_EXE=java.exe
42 | %JAVA_EXE% -version >NUL 2>&1
43 | if "%ERRORLEVEL%" == "0" goto execute
44 |
45 | echo.
46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
47 | echo.
48 | echo Please set the JAVA_HOME variable in your environment to match the
49 | echo location of your Java installation.
50 |
51 | goto fail
52 |
53 | :findJavaFromJavaHome
54 | set JAVA_HOME=%JAVA_HOME:"=%
55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
56 |
57 | if exist "%JAVA_EXE%" goto execute
58 |
59 | echo.
60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
61 | echo.
62 | echo Please set the JAVA_HOME variable in your environment to match the
63 | echo location of your Java installation.
64 |
65 | goto fail
66 |
67 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if "%ERRORLEVEL%"=="0" goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
84 | exit /b 1
85 |
86 | :mainEnd
87 | if "%OS%"=="Windows_NT" endlocal
88 |
89 | :omega
90 |
--------------------------------------------------------------------------------
/settings.gradle.kts:
--------------------------------------------------------------------------------
1 | pluginManagement {
2 | repositories {
3 | google()
4 | gradlePluginPortal()
5 | mavenCentral()
6 | }
7 | }
8 |
9 | dependencyResolutionManagement {
10 | repositories {
11 | google()
12 | mavenCentral()
13 | }
14 | }
15 |
16 | rootProject.name = "AutoLinkText"
17 | include(":demoApp:composeApp")
18 | include(":autolinktext")
--------------------------------------------------------------------------------