Skip to content

Commit

Permalink
Add auto URL detection to info commands
Browse files Browse the repository at this point in the history
Signed-off-by: applenick <[email protected]>
  • Loading branch information
applenick committed Sep 28, 2024
1 parent 4317335 commit 1ad4ba7
Showing 1 changed file with 30 additions and 1 deletion.
31 changes: 30 additions & 1 deletion src/main/java/dev/pgm/community/info/InfoCommandData.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,16 @@
import static net.kyori.adventure.text.Component.text;

import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.event.ClickEvent;
import net.kyori.adventure.text.event.HoverEvent;
import net.kyori.adventure.text.format.NamedTextColor;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.ConfigurationSection;
import tc.oc.pgm.util.Audience;
import tc.oc.pgm.util.text.TextException;
import tc.oc.pgm.util.text.TextParser;

public class InfoCommandData {
Expand All @@ -29,11 +34,35 @@ public static InfoCommandData of(ConfigurationSection section) {
return new InfoCommandData(
section.getName(),
section.getStringList(LINES_KEY).stream()
.map(TextParser::parseComponent)
.map(line -> {
try {
Component parsedComponent = TextParser.parseComponent(line);
return addUrlEventsToComponent(parsedComponent);
} catch (TextException e) {
e.printStackTrace();
return Component.text(line); // Fallback if error
}
})
.collect(Collectors.toList()),
section.getString(PERMISSION_KEY));
}

private static final Pattern URL_PATTERN = Pattern.compile(
"(https?://[\\w\\-\\.]+(:\\d+)?(/[\\w\\-\\./?%&=]*)?)", Pattern.CASE_INSENSITIVE);

private static Component addUrlEventsToComponent(Component component) {
return component.replaceText(
builder -> builder.match(URL_PATTERN).replacement((matchResult, textComponentBuilder) -> {
String url = matchResult.group();
return Component.text(url)
.color(NamedTextColor.BLUE)
.hoverEvent(HoverEvent.showText(Component.text()
.append(Component.text("Click to open ", NamedTextColor.GRAY))
.append(Component.text(url, NamedTextColor.BLUE))))
.clickEvent(ClickEvent.openUrl(url));
}));
}

public String getName() {
return name;
}
Expand Down

0 comments on commit 1ad4ba7

Please sign in to comment.