From b12fbfa3555180ef771a8954731056a4cf1e68df Mon Sep 17 00:00:00 2001 From: LucasGGamerM Date: Wed, 16 Apr 2025 13:01:56 -0300 Subject: [PATCH] refactor(StatusTextEncoder.java): add back this utility Why do I still do this aaaaaaaaaaaa --- .../android/utils/StatusTextEncoder.java | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 mastodon/src/main/java/org/joinmastodon/android/utils/StatusTextEncoder.java diff --git a/mastodon/src/main/java/org/joinmastodon/android/utils/StatusTextEncoder.java b/mastodon/src/main/java/org/joinmastodon/android/utils/StatusTextEncoder.java new file mode 100644 index 000000000..7bf862178 --- /dev/null +++ b/mastodon/src/main/java/org/joinmastodon/android/utils/StatusTextEncoder.java @@ -0,0 +1,61 @@ +package org.joinmastodon.android.utils; + +import android.util.Pair; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Function; +import java.util.regex.MatchResult; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +// not a good class +public class StatusTextEncoder { + private final Function fn; + + // see ComposeFragment.HIGHLIGHT_PATTERN + private final static Pattern EXCLUDE_PATTERN = Pattern.compile("\\s*(?:@([a-zA-Z0-9_]+)(@[a-zA-Z0-9_.-]+)?|#([^\\s.]+))\\s*"); + + public StatusTextEncoder(Function fn) { + this.fn = fn; + } + + // prettiest method award winner 2023 [citation needed] + public String encode(String content) { + StringBuilder encodedString = new StringBuilder(); + // matches mentions and hashtags + Matcher m = EXCLUDE_PATTERN.matcher(content); + int previousEnd = 0; + while (m.find()) { + MatchResult res = m.toMatchResult(); + // everything before the match - do encode + encodedString.append(fn.apply(content.substring(previousEnd, res.start()))); + previousEnd = res.end(); + // the match - do not encode + encodedString.append(res.group()); + } + // everything after the last match - do encode + encodedString.append(fn.apply(content.substring(previousEnd))); + return encodedString.toString(); + } + + // prettiest almost-exact replica of a pretty function + public Pair> decode(String content, Pattern regex) { + Matcher m=regex.matcher(content); + StringBuilder decodedString=new StringBuilder(); + List decodedParts=new ArrayList<>(); + int previousEnd=0; + while (m.find()) { + MatchResult res=m.toMatchResult(); + // everything before the match - do not decode + decodedString.append(content.substring(previousEnd, res.start())); + previousEnd=res.end(); + // the match - do decode + String decoded=fn.apply(res.group()); + decodedParts.add(decoded); + decodedString.append(decoded); + } + decodedString.append(content.substring(previousEnd)); + return Pair.create(decodedString.toString(), decodedParts); + } +}