Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Try avoiding trailing punctuation inside linkified URLs #4214

Merged

Conversation

jmartinesp
Copy link
Member

Content

When an URL is linkified automatically by LinkifyCompat, try removing any trailing punctuation and other mismatched symbols from the link span.

This solution is not great and might fail in some cases, but it should cover the most common ones, since it seems like a 'smart' linkification library is hard to find as a replacement.

Motivation and context

It turns out the Linkify component from Google isn't as smart as we thought: as soon as a / char is found inside the URL, it'll greedily fetch as much text as possible. This is probably because a different regex is used internally than for a simple domain.

Should fix #4208.

Screenshots / GIFs

Before After
image image

Tests

You can play with the ClickableLinkTextWithParenthesisPreview composable preview, or send messages with URLs and problematic formats to be linkified.

Tested devices

  • Physical
  • Emulator
  • OS version(s): 14

Checklist

  • Changes have been tested on an Android device or Android emulator with API 24
  • UI change has been tested on both light and dark themes
  • Accessibility has been taken into account. See https://github.com/element-hq/element-x-android/blob/develop/CONTRIBUTING.md#accessibility
  • Pull request is based on the develop branch
  • Pull request title will be used in the release note, it clearly define what will change for the user
  • Pull request includes screenshots or videos if containing UI changes
  • You've made a self review of your PR

@jmartinesp jmartinesp added the PR-Bugfix For bug fix label Jan 29, 2025
@jmartinesp jmartinesp requested a review from a team as a code owner January 29, 2025 10:02
@jmartinesp jmartinesp requested review from bmarty and removed request for a team January 29, 2025 10:02
Copy link
Contributor

github-actions bot commented Jan 29, 2025

📱 Scan the QR code below to install the build (arm64 only) for this PR.
QR code
If you can't scan the QR code you can install the build via this link: https://i.diawi.com/VcdaPo

@Composable
internal fun ClickableLinkTextWithParenthesisPreview() = ElementThemedPreview {
ClickableLinkText(
annotatedString = AnnotatedString("Does this work (url: github.com/element-hq/element-x-android/README?)?!.", ParagraphStyle()),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe add exemple where parenthesis is part of the url?

Copy link

codecov bot commented Jan 29, 2025

Codecov Report

Attention: Patch coverage is 86.36364% with 6 lines in your changes missing coverage. Please review.

Project coverage is 80.13%. Comparing base (a3732fe) to head (d1fb2fd).
Report is 9 commits behind head on develop.

Files with missing lines Patch % Lines
...droid/libraries/androidutils/text/LinkifyHelper.kt 85.00% 1 Missing and 5 partials ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #4214      +/-   ##
===========================================
- Coverage    80.13%   80.13%   -0.01%     
===========================================
  Files         2052     2053       +1     
  Lines        54576    54601      +25     
  Branches      6672     6683      +11     
===========================================
+ Hits         43733    43752      +19     
- Misses        8560     8561       +1     
- Partials      2283     2288       +5     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link
Member

@bmarty bmarty left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, I have tested and the target link need to be updated as well.

end = adjustEndIndex(spannable, start, end)
}.onFailure {
Timber.e(it, "Failed to adjust end index for link span")
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is adjusting the end of the span, so this is fixing the rendering issue, but it does this affect the URL itself, i.e. the target of the link.

I think the line annotation = span.url, below needs to be updated.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's maybe because it did not work with the example I tried:

image

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does the Event renderer use ClickableLinkText? It seems it's not the case 😅

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ahhh damn, it used to use it, that's why I tried fixing it here. I'll move the code where it belongs 🥲 .

@jmartinesp jmartinesp force-pushed the fix/jme/avoid-trailing-punctuation-in-linkified-urls branch from 9ef2d3f to 323c811 Compare January 29, 2025 17:03
@jmartinesp jmartinesp requested a review from bmarty January 30, 2025 09:28
@jmartinesp
Copy link
Member Author

This should be ready to review again: it's now affecting the intended texts (🤦 ) and has some extra unit tests for the new component.

Copy link
Member

@bmarty bmarty left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks and sorry for the late review. Good to be merged, I believe that I wrote only non-blocking remarks.

return spannable
}
private fun CharSequence.withFixedURLSpans(): CharSequence {
return LinkifyHelper.linkify(this, Linkify.WEB_URLS or Linkify.PHONE_NUMBERS or Linkify.EMAIL_ADDRESSES)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe remove the second param, since it's the default value.
Also maybe move this extension to the file LinkifyHelper and rename it to safeLinkify(), cleverLinkify(), betterLinkify() or something better (can't find something good).

@Composable
internal fun TimelineItemTextViewWithLinkifiedUrlPreview() = ElementPreview {
val content = aTimelineItemTextContent(
pillifiedBody = LinkifyHelper.linkify("Does this work (url: github.com/element-hq/element-x-android/README?)?.")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe change the text to

Suggested change
pillifiedBody = LinkifyHelper.linkify("Does this work (url: github.com/element-hq/element-x-android/README?)?.")
pillifiedBody = LinkifyHelper.linkify("The link should end after the first '?' (url: github.com/element-hq/element-x-android/README?)?.")

@Composable
internal fun TimelineItemTextViewWithLinkifiedUrlAndNestedParenthesisPreview() = ElementPreview {
val content = aTimelineItemTextContent(
pillifiedBody = LinkifyHelper.linkify("Does this work ((url: github.com/element-hq/element-x-android/READ(ME)))!")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe change the text to

Suggested change
pillifiedBody = LinkifyHelper.linkify("Does this work ((url: github.com/element-hq/element-x-android/READ(ME)))!")
pillifiedBody = LinkifyHelper.linkify("The link should end after the '(ME)' ((url: github.com/element-hq/element-x-android/READ(ME)))!")

fun `linkification finds URL`() {
val text = "A url https://matrix.org"
val result = LinkifyHelper.linkify(text)
val urlSpans = result.toSpannable().getSpans<URLSpan>(start = 0, end = result.length)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All the start = 0, end = result.length in all tests are not necessary, the 2 parameters are the default values.

// Restore old spans, remove new ones if there is a conflict
for ((urlSpan, location) in oldURLSpans) {
val (start, end) = location
val addedConflictingSpans = spannable.getSpans<URLSpan>(start, end).orEmpty()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

.orEmpty() does not seem to be necessary.

For tests, I think the function will return before, at line 29.

assertThat(urlSpans.size).isEqualTo(1)
assertThat(urlSpans.first().url).isEqualTo("https://github.com/element-hq/element-android/READ(ME)")
}
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for all those tests!

Create `LinkfierHelper` and post-process URLSpans added to make sure they honor the actual URLs in text by removing unnecessarily added trailing punctuation.
@jmartinesp jmartinesp force-pushed the fix/jme/avoid-trailing-punctuation-in-linkified-urls branch from 28c8e82 to a35a96c Compare February 21, 2025 15:36
@jmartinesp jmartinesp enabled auto-merge (squash) February 21, 2025 15:36
@jmartinesp jmartinesp added the Record-Screenshots Runs the 'Record Screenshots' CI job and adds a commit with any new screenshots found. label Feb 21, 2025
@github-actions github-actions bot removed the Record-Screenshots Runs the 'Record Screenshots' CI job and adds a commit with any new screenshots found. label Feb 21, 2025
@jmartinesp jmartinesp merged commit 5d8403b into develop Feb 21, 2025
26 checks passed
@jmartinesp jmartinesp deleted the fix/jme/avoid-trailing-punctuation-in-linkified-urls branch February 21, 2025 16:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
PR-Bugfix For bug fix
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Linkified text is too greedy and gobbles punctuation
4 participants