Skip to content

Commit

Permalink
Add static toLegacyText varargs method with context-aware arguments a…
Browse files Browse the repository at this point in the history
…nd add test for it
  • Loading branch information
Janmm14 committed Apr 14, 2024
1 parent 0bbe3e6 commit dc7fecd
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 4 deletions.
23 changes: 19 additions & 4 deletions chat/src/main/java/net/md_5/bungee/api/chat/BaseComponent.java
Expand Up @@ -213,14 +213,29 @@ public BaseComponent duplicateWithoutFormatting()
public static String toLegacyText(BaseComponent... components)
{
StringBuilder builder = new StringBuilder();
ComponentStyle currentStyle = new ComponentStyle();
currentStyle.setColor( ChatColor.RESET );
ComponentStyle currentLegacy = new ComponentStyle();
currentLegacy.setColor( ChatColor.RESET );

toLegacyText( builder, currentLegacy, components );
return builder.toString();
}

/**
* Converts the components to a string that uses the old formatting codes
* ({@link net.md_5.bungee.api.ChatColor#COLOR_CHAR}
*
* @param builder the StringBuilder to append to
* @param currentLegacy the style at the end of {@code builder}
* @param components the components to convert
* @return the style at the end of the legacy string
*/
public static ComponentStyle toLegacyText(StringBuilder builder, ComponentStyle currentLegacy, BaseComponent... components)
{
for ( BaseComponent msg : components )
{
currentStyle = msg.toLegacyText( builder, currentStyle );
currentLegacy = msg.toLegacyText( builder, currentLegacy );
}
return builder.toString();
return currentLegacy;
}

/**
Expand Down
18 changes: 18 additions & 0 deletions chat/src/test/java/net/md_5/bungee/api/chat/ComponentsTest.java
Expand Up @@ -3,6 +3,7 @@
import static net.md_5.bungee.api.ChatColor.*;
import static org.junit.jupiter.api.Assertions.*;
import java.awt.Color;
import java.util.Arrays;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
Expand Down Expand Up @@ -905,4 +906,21 @@ public void testExtraFormattingNested()
// see TextComponent#toLegacyText comment as to why we keep it
assertEquals( GOLD + "Hello " + BOLD + "World" + GOLD + RED + "!" + GOLD + " xd", component.toLegacyText() );
}

@Test
public void testArrayToLegacyConversionContext()
{
TextComponent world = new TextComponent( "World" );
world.setBold( true );
BaseComponent[] components = new BaseComponent[]
{
new TextComponent( "Hello " ),
world,
new TextComponent( "!" )
};
System.out.println( "components = " + Arrays.toString( components ) );

assertEquals( "Hello World!", BaseComponent.toPlainText( components ) );
assertEquals( "Hello " + BOLD + "World" + RESET + "!", BaseComponent.toLegacyText( components ) );
}
}

0 comments on commit dc7fecd

Please sign in to comment.