From ec6c646f6f44e7c15bf07e8c0df6198d67d6b8a3 Mon Sep 17 00:00:00 2001 From: Des Herriott Date: Fri, 19 Jul 2024 10:54:36 +0100 Subject: [PATCH] chore: added ClientTextComponentUtils.ellipsize() --- .../util/client/ClientTextComponentUtils.java | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/common/src/main/java/dev/ftb/mods/ftblibrary/util/client/ClientTextComponentUtils.java b/common/src/main/java/dev/ftb/mods/ftblibrary/util/client/ClientTextComponentUtils.java index ce7ce758..43184b81 100644 --- a/common/src/main/java/dev/ftb/mods/ftblibrary/util/client/ClientTextComponentUtils.java +++ b/common/src/main/java/dev/ftb/mods/ftblibrary/util/client/ClientTextComponentUtils.java @@ -3,6 +3,7 @@ import dev.ftb.mods.ftblibrary.util.CustomComponentParser; import dev.ftb.mods.ftblibrary.util.StringUtils; import dev.ftb.mods.ftblibrary.util.TextComponentParser; +import net.minecraft.client.gui.Font; import net.minecraft.client.resources.language.I18n; import net.minecraft.network.chat.*; @@ -10,6 +11,8 @@ import java.util.List; import java.util.function.Function; +import static net.minecraft.network.chat.CommonComponents.ELLIPSIS; + public class ClientTextComponentUtils { private static final Function DEFAULT_STRING_TO_COMPONENT = ClientTextComponentUtils::defaultStringToComponent; @@ -59,4 +62,15 @@ private static Component defaultStringToComponent(String s) { return parse(I18n.get(s)); } + + public static FormattedText ellipsize(Font font, FormattedText text, int maxWidth) { + final int strWidth = font.width(text); + final int ellipsisWidth = font.width(ELLIPSIS); + if (strWidth > maxWidth) { + return ellipsisWidth >= maxWidth ? + font.substrByWidth(text, maxWidth) : + FormattedText.composite(font.substrByWidth(text, maxWidth - ellipsisWidth), ELLIPSIS); + } + return text; + } }