Skip to content

Commit

Permalink
Fix repeating hashtag not highlighting in note content (#256)
Browse files Browse the repository at this point in the history
  • Loading branch information
mehmedalijaK authored Dec 16, 2024

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature.
1 parent e457783 commit 594e54d
Showing 3 changed files with 32 additions and 7 deletions.
18 changes: 12 additions & 6 deletions app/src/main/kotlin/net/primal/android/core/utils/TextMatcher.kt
Original file line number Diff line number Diff line change
@@ -3,6 +3,7 @@ package net.primal.android.core.utils
class TextMatcher(
content: String,
texts: List<String>,
repeatingOccurrences: Boolean = false,
) {

private val matches: MutableList<TextMatch> = mutableListOf()
@@ -26,16 +27,21 @@ class TextMatcher(
}

init {
texts.forEach {
val startIndex = content.indexOfNotMatchedBefore(text = it)
if (startIndex != null) {
texts.forEach { text ->
var currentIndex = content.indexOfNotMatchedBefore(text = text)

while (currentIndex != null) {
matches.add(
TextMatch(
value = it,
startIndex = startIndex,
endIndex = startIndex + it.length,
value = text,
startIndex = currentIndex,
endIndex = currentIndex + text.length,
),
)

if (!repeatingOccurrences) break

currentIndex = content.indexOfNotMatchedBefore(text = text)
}
}
}
Original file line number Diff line number Diff line change
@@ -393,7 +393,11 @@ fun renderContentAsAnnotatedString(
)
}

TextMatcher(content = refinedContent, texts = data.hashtags)
TextMatcher(
content = refinedContent,
texts = data.hashtags,
repeatingOccurrences = true,
)
.matches()
.forEach {
addHashtagAnnotation(
Original file line number Diff line number Diff line change
@@ -2,6 +2,7 @@ package net.primal.android.core.utils

import io.kotest.matchers.collections.shouldContain
import io.kotest.matchers.collections.shouldContainAll
import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder
import io.kotest.matchers.collections.shouldNotContain
import org.junit.Test

@@ -31,6 +32,20 @@ class TextMatcherTest {
actual.shouldContainAll(hashtags)
}

@Test
fun `matches should match hashtags and return hashtags with duplicates`() {
val hashtags = listOf("#nostr", "#bitcoin", "#sats", "#freedom")
val expected = listOf("#nostr", "#nostr", "#nostr", "#bitcoin", "#freedom", "#freedom", "#sats")
val matcher = TextMatcher(
content = "Hello I love #nostr #nostr somemore #nostr #bitcoin #freedom #sats #freedom",
texts = hashtags,
repeatingOccurrences = true,
)

val actual = matcher.matches().map { it.value }
actual.shouldContainExactlyInAnyOrder(expected)
}

@Test
fun `matches should not match unknown hashtags`() {
val hashtags = listOf("#Hiking", "#Trails")

0 comments on commit 594e54d

Please sign in to comment.