DREAMFIRE Docs ← Back to site
Loading...
Searching...
No Matches
DreamMessageFormatter.java
Go to the documentation of this file.
1/*
2 * MIT License
3 *
4 * Copyright (c) 2025 Dreamfire Studio
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in all
14 * copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 * SOFTWARE.
23 */
24package com.dreamfirestudios.dreamcore.DreamChat;
25
26import me.clip.placeholderapi.PlaceholderAPI;
27import net.kyori.adventure.text.Component;
28import net.kyori.adventure.text.minimessage.MiniMessage;
29import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder;
30import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver;
31import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
32import org.bukkit.Bukkit;
33import org.bukkit.entity.Player;
34import org.jetbrains.annotations.NotNull;
35import org.jetbrains.annotations.Nullable;
36
37import java.util.Locale;
38import java.util.Objects;
39import java.util.regex.Pattern;
40
53public final class DreamMessageFormatter {
54
55 private DreamMessageFormatter() {}
56
57 private static final MiniMessage MM = MiniMessage.miniMessage();
58
59 // Basic scrubbers for when MiniMessage or specific tag families are disabled in settings
60 private static final Pattern COLOR_TAGS = Pattern.compile(
61 "</?#[0-9a-fA-F]{6}>|</?color(?:\\s*:\\s*#[0-9a-fA-F]{6})?>|</?gradient(?:\\s*:[^>]+)?>|</?rainbow(?:\\s*:[^>]+)?>"
62 );
63 private static final Pattern FORMAT_TAGS = Pattern.compile(
64 "</?(bold|b|italic|i|underlined|u|strikethrough|st|obfuscated|obf)>"
65 );
66 private static final Pattern ACTION_TAGS = Pattern.compile(
67 "</?click(?:\\s*:[^>]+)?>|</?hover(?:\\s*:[^>]+)?>"
68 );
69
70 // ---------------------------------------------------------------------
71 // Public API — String -> Component
72 // ---------------------------------------------------------------------
73
80 public static @NotNull Component format(@Nullable String message,
81 @Nullable DreamMessageSettings settings) {
82 return format(message, null, settings);
83 }
84
93 public static @NotNull Component format(@Nullable String message,
94 @Nullable Player player,
95 @Nullable DreamMessageSettings settings,
96 TagResolver... resolvers) {
97 if (message == null) return Component.empty();
98 final DreamMessageSettings s = nonNull(settings);
99
100 String processed = message;
101 if (s.usePlaceholders() && player != null && isPapiAvailable()) {
102 processed = PlaceholderAPI.setPlaceholders(player, processed);
103 }
104
105 if (!s.allowMiniMessage()) {
106 // Sanitization strips MiniMessage tags if disallowed; then emit as plain text.
107 processed = sanitize(processed, s);
108 return Component.text(processed);
109 }
110
111 processed = sanitize(processed, s);
112 final TagResolver resolver = (resolvers != null && resolvers.length > 0)
113 ? TagResolver.resolver(resolvers)
114 : TagResolver.empty();
115 return MM.deserialize(processed, resolver);
116 }
117
125 public static @NotNull Component format(@Nullable String message,
126 @Nullable Player player,
127 @Nullable DreamMessageSettings settings) {
128 return format(message, player, settings, TagResolver.empty());
129 }
130
131 // ---------------------------------------------------------------------
132 // Public API — Component -> Component
133 // ---------------------------------------------------------------------
134
143 public static @NotNull Component format(@Nullable Component component,
144 @Nullable DreamMessageSettings settings) {
145 return format(component, null, settings, TagResolver.empty());
146 }
147
156 public static @NotNull Component format(@Nullable Component component,
157 @Nullable Player player,
158 @Nullable DreamMessageSettings settings,
159 TagResolver... resolvers) {
160 if (component == null) return Component.empty();
161 final DreamMessageSettings s = nonNull(settings);
162
163 // If no MiniMessage or no placeholders are needed, return as-is (minor optimization).
164 if (!s.allowMiniMessage() && !(s.usePlaceholders() && player != null && isPapiAvailable())) {
165 return component;
166 }
167
168 // Serialize to MiniMessage so PAPI & sanitization operate on a string representation.
169 String mm = MM.serialize(component);
170
171 if (s.usePlaceholders() && player != null && isPapiAvailable()) {
172 mm = PlaceholderAPI.setPlaceholders(player, mm);
173 }
174
175 mm = sanitize(mm, s);
176
177 final TagResolver resolver = (resolvers != null && resolvers.length > 0)
178 ? TagResolver.resolver(resolvers)
179 : TagResolver.empty();
180
181 return MM.deserialize(mm, resolver);
182 }
183
184 // ---------------------------------------------------------------------
185 // Helpers — presentation utilities
186 // ---------------------------------------------------------------------
187
194 public static @Nullable String centerMessage(@Nullable String message, int width) {
195 if (message == null) return null;
196 final int w = Math.max(width, message.length());
197 final int pad = w - message.length();
198 final int left = pad / 2;
199 final int right = pad - left;
200 return " ".repeat(left) + message + " ".repeat(right);
201 // For proportional fonts, consider pixel-width centering instead.
202 }
203
210 public static @NotNull Component centerMessage(@NotNull Component component, int width) {
211 final String plain = PlainTextComponentSerializer.plainText().serialize(component);
212 final String centered = centerMessage(plain, width);
213 return Component.text(centered == null ? "" : centered);
214 }
215
222 public static @NotNull String limitMessage(@Nullable String message, int maxLen) {
223 if (message == null || maxLen <= 0) return "...";
224 if (message.length() <= maxLen) return message;
225 return message.substring(0, Math.max(0, maxLen)) + "...";
226 }
227
234 public static @NotNull Component limitMessage(@NotNull Component component, int maxLen) {
235 final String plain = PlainTextComponentSerializer.plainText().serialize(component);
236 return Component.text(limitMessage(plain, maxLen));
237 }
238
244 public static @Nullable String capitalizeWords(@Nullable String message) {
245 if (message == null || message.isEmpty()) return message;
246 String[] words = message.split(" ");
247 StringBuilder sb = new StringBuilder(message.length());
248 for (String w : words) {
249 if (w.isEmpty()) continue;
250 sb.append(Character.toUpperCase(w.charAt(0)))
251 .append(w.substring(1).toLowerCase(Locale.ROOT))
252 .append(' ');
253 }
254 return sb.toString().trim();
255 }
256
262 public static @Nullable String reverseMessage(@Nullable String message) {
263 if (message == null) return null;
264 return new StringBuilder(message).reverse().toString();
265 }
266
267 // ---------------------------------------------------------------------
268 // Placeholder helpers
269 // ---------------------------------------------------------------------
270
277 public static @NotNull TagResolver placeholder(@NotNull String key, @Nullable String value) {
278 return Placeholder.unparsed(key, value == null ? "" : value);
279 }
280
287 public static @NotNull TagResolver placeholder(@NotNull String key, @NotNull Component value) {
288 return Placeholder.component(key, value);
289 }
290
291 // ---------------------------------------------------------------------
292 // Internals
293 // ---------------------------------------------------------------------
294
298 private static boolean isPapiAvailable() {
299 return Bukkit.getPluginManager().isPluginEnabled("PlaceholderAPI");
300 }
301
305 private static @NotNull DreamMessageSettings nonNull(@Nullable DreamMessageSettings s) {
306 return Objects.requireNonNullElse(s, DreamMessageSettings.all());
307 }
308
316 private static @NotNull String sanitize(@NotNull String input, @NotNull DreamMessageSettings s) {
317 String out = input;
318 if (!s.allowColors()) {
319 out = COLOR_TAGS.matcher(out).replaceAll("");
320 }
321 if (!s.allowFormatting()) {
322 out = FORMAT_TAGS.matcher(out).replaceAll("");
323 }
324 if (!s.allowClickAndHover()) {
325 out = ACTION_TAGS.matcher(out).replaceAll("");
326 }
327 return out;
328 }
329}
Adventure‑first message formatter that supports: MiniMessage parsing (configurable via DreamMessageSe...
static String limitMessage(@Nullable String message, int maxLen)
Truncates a string to maxLen characters and appends ellipsis when needed.
static Component limitMessage(@NotNull Component component, int maxLen)
Truncates a component's plain‑text view and returns a plain text component.
static String centerMessage(@Nullable String message, int width)
Centers a string to a given width using spaces (monospaced display assumption).
static TagResolver placeholder(@NotNull String key, @Nullable String value)
Creates an unparsed placeholder (MiniMessage <key> replaced with literal value).
static String reverseMessage(@Nullable String message)
Reverses a string.
static Component format(@Nullable Component component, @Nullable DreamMessageSettings settings)
Pass‑through formatting for a Component.
static Component format(@Nullable String message, @Nullable DreamMessageSettings settings)
Formats a raw string to an Adventure Component using settings.
static Component format(@Nullable Component component, @Nullable Player player, @Nullable DreamMessageSettings settings, TagResolver... resolvers)
Full control formatting for a Component with PAPI and MiniMessage resolvers.
static String capitalizeWords(@Nullable String message)
Capitalizes every word in a string (simple ASCII rules).
static Component format(@Nullable String message, @Nullable Player player, @Nullable DreamMessageSettings settings)
Formats a raw string with optional PlaceholderAPI expansion for the given player.
static Component format(@Nullable String message, @Nullable Player player, @Nullable DreamMessageSettings settings, TagResolver... resolvers)
Formats a raw string with optional PlaceholderAPI expansion for the given player.
static TagResolver placeholder(@NotNull String key, @NotNull Component value)
Creates a component placeholder (MiniMessage <key> replaced with a component).
static Component centerMessage(@NotNull Component component, int width)
Centers a Component by converting to plain text, centering, then returning as plain text.
record DreamMessageSettings(boolean usePlaceholders, boolean allowMiniMessage, boolean allowColors, boolean allowFormatting, boolean allowClickAndHover)
Immutable settings that control how DreamMessageFormatter processes messages.