|
| 1 | +/* |
| 2 | + * Copyright 2025 New Vector Ltd. |
| 3 | + * |
| 4 | + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial |
| 5 | + * Please see LICENSE files in the repository root for full details. |
| 6 | + */ |
| 7 | + |
| 8 | +package io.element.android.libraries.androidutils.text |
| 9 | + |
| 10 | +import android.text.Spannable |
| 11 | +import android.text.style.URLSpan |
| 12 | +import android.text.util.Linkify |
| 13 | +import androidx.core.text.getSpans |
| 14 | +import androidx.core.text.toSpannable |
| 15 | +import androidx.core.text.util.LinkifyCompat |
| 16 | +import timber.log.Timber |
| 17 | +import kotlin.collections.component1 |
| 18 | +import kotlin.collections.component2 |
| 19 | +import kotlin.collections.isNotEmpty |
| 20 | +import kotlin.collections.iterator |
| 21 | +import kotlin.collections.orEmpty |
| 22 | + |
| 23 | +/** |
| 24 | + * Helper class to linkify text while preserving existing URL spans. |
| 25 | + * |
| 26 | + * It also checks the linkified results to make sure URLs spans are not including trailing punctuation. |
| 27 | + */ |
| 28 | +object LinkifyHelper { |
| 29 | + fun linkify( |
| 30 | + text: CharSequence, |
| 31 | + @LinkifyCompat.LinkifyMask linkifyMask: Int = Linkify.WEB_URLS or Linkify.PHONE_NUMBERS or Linkify.EMAIL_ADDRESSES, |
| 32 | + ): CharSequence { |
| 33 | + // Convert the text to a Spannable to be able to add URL spans, return the original text if it's not possible (in tests, i.e.) |
| 34 | + val spannable = text.toSpannable() ?: return text |
| 35 | + |
| 36 | + // Get all URL spans, as they will be removed by LinkifyCompat.addLinks |
| 37 | + val oldURLSpans = spannable.getSpans<URLSpan>(0, text.length).associateWith { |
| 38 | + val start = spannable.getSpanStart(it) |
| 39 | + val end = spannable.getSpanEnd(it) |
| 40 | + Pair(start, end) |
| 41 | + } |
| 42 | + // Find and set as URLSpans any links present in the text |
| 43 | + val addedNewLinks = LinkifyCompat.addLinks(spannable, linkifyMask) |
| 44 | + |
| 45 | + // Process newly added URL spans |
| 46 | + if (addedNewLinks) { |
| 47 | + val newUrlSpans = spannable.getSpans<URLSpan>(0, spannable.length) |
| 48 | + for (urlSpan in newUrlSpans) { |
| 49 | + val start = spannable.getSpanStart(urlSpan) |
| 50 | + val end = spannable.getSpanEnd(urlSpan) |
| 51 | + |
| 52 | + // Try to avoid including trailing punctuation in the link. |
| 53 | + // Since this might fail in some edge cases, we catch the exception and just use the original end index. |
| 54 | + val newEnd = runCatching { |
| 55 | + adjustLinkifiedUrlSpanEndIndex(spannable, start, end) |
| 56 | + }.onFailure { |
| 57 | + Timber.e(it, "Failed to adjust end index for link span") |
| 58 | + }.getOrNull() ?: end |
| 59 | + |
| 60 | + // Adapt the url in the URL span to the new end index too if needed |
| 61 | + if (end != newEnd) { |
| 62 | + val url = spannable.subSequence(start, newEnd).toString() |
| 63 | + spannable.removeSpan(urlSpan) |
| 64 | + spannable.setSpan(URLSpan(url), start, newEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) |
| 65 | + } else { |
| 66 | + spannable.setSpan(urlSpan, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) |
| 67 | + } |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + // Restore old spans, remove new ones if there is a conflict |
| 72 | + for ((urlSpan, location) in oldURLSpans) { |
| 73 | + val (start, end) = location |
| 74 | + val addedConflictingSpans = spannable.getSpans<URLSpan>(start, end) |
| 75 | + if (addedConflictingSpans.isNotEmpty()) { |
| 76 | + for (span in addedConflictingSpans) { |
| 77 | + spannable.removeSpan(span) |
| 78 | + } |
| 79 | + } |
| 80 | + |
| 81 | + spannable.setSpan(urlSpan, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) |
| 82 | + } |
| 83 | + return spannable |
| 84 | + } |
| 85 | + |
| 86 | + private fun adjustLinkifiedUrlSpanEndIndex(spannable: Spannable, start: Int, end: Int): Int { |
| 87 | + var end = end |
| 88 | + |
| 89 | + // Trailing punctuation found, adjust the end index |
| 90 | + while (spannable[end - 1] in sequenceOf('.', ',', ';', ':', '!', '?', '…') && end > start) { |
| 91 | + end-- |
| 92 | + } |
| 93 | + |
| 94 | + // If the last character is a closing parenthesis, check if it's part of a pair |
| 95 | + if (spannable[end - 1] == ')' && end > start) { |
| 96 | + val linkifiedTextLastPath = spannable.substring(start, end).substringAfterLast('/') |
| 97 | + val closingParenthesisCount = linkifiedTextLastPath.count { it == ')' } |
| 98 | + val openingParenthesisCount = linkifiedTextLastPath.count { it == '(' } |
| 99 | + // If it's not part of a pair, remove it from the link span by adjusting the end index |
| 100 | + end -= closingParenthesisCount - openingParenthesisCount |
| 101 | + } |
| 102 | + return end |
| 103 | + } |
| 104 | +} |
| 105 | + |
| 106 | +/** |
| 107 | + * Linkify the text with the default mask (WEB_URLS, PHONE_NUMBERS, EMAIL_ADDRESSES). |
| 108 | + */ |
| 109 | +fun CharSequence.safeLinkify(): CharSequence { |
| 110 | + return LinkifyHelper.linkify(this, Linkify.WEB_URLS or Linkify.PHONE_NUMBERS or Linkify.EMAIL_ADDRESSES) |
| 111 | +} |
0 commit comments