-
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Linkify summary in TalkingKotlinEpisode.
- Loading branch information
1 parent
dbfabde
commit 06d14f5
Showing
3 changed files
with
58 additions
and
17 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
42 changes: 42 additions & 0 deletions
42
...ava/io/github/reactivecircus/kstreamlined/android/feature/talkingkotlinepisode/linkify.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
package io.github.reactivecircus.kstreamlined.android.feature.talkingkotlinepisode | ||
|
||
import android.text.SpannableString | ||
import android.text.style.URLSpan | ||
import android.text.util.Linkify | ||
import androidx.compose.ui.text.AnnotatedString | ||
import androidx.compose.ui.text.SpanStyle | ||
import androidx.compose.ui.text.buildAnnotatedString | ||
|
||
/** | ||
* Adopted from https://stackoverflow.com/a/73662287 | ||
*/ | ||
internal fun String.linkify( | ||
linkStyle: SpanStyle | ||
): AnnotatedString = buildAnnotatedString { | ||
append(this@linkify) | ||
val spannable = SpannableString(this@linkify) | ||
Linkify.addLinks(spannable, Linkify.WEB_URLS) | ||
val spans = spannable.getSpans(0, spannable.length, URLSpan::class.java) | ||
for (span in spans) { | ||
val start = spannable.getSpanStart(span) | ||
val end = spannable.getSpanEnd(span) | ||
addStyle( | ||
start = start, | ||
end = end, | ||
style = linkStyle, | ||
) | ||
addStringAnnotation( | ||
tag = UrlTag, | ||
annotation = span.url, | ||
start = start, | ||
end = end, | ||
) | ||
} | ||
} | ||
|
||
internal fun AnnotatedString.findUrl(offset: Int): String? = | ||
getStringAnnotations(UrlTag, offset, offset) | ||
.firstOrNull() | ||
?.item | ||
|
||
private const val UrlTag = "URL" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters