aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/com/anthonyhilyard/iceberg/util/StringRecomposer.java
blob: 4ad448d15cf2e8211362455346ff84715d62ccd2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package com.anthonyhilyard.iceberg.util;

import java.util.ArrayList;
import java.util.List;

import net.minecraft.client.gui.screens.inventory.tooltip.ClientTextTooltip;
import net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipComponent;
import net.minecraft.network.chat.FormattedText;
import net.minecraft.network.chat.MutableComponent;
import net.minecraft.network.chat.Style;
import net.minecraft.network.chat.TextComponent;
import net.minecraft.util.FormattedCharSink;

public class StringRecomposer
{
	public static List<FormattedText> recompose(List<ClientTooltipComponent> components)
	{
		List<FormattedText> recomposedLines = new ArrayList<>();
		for (ClientTooltipComponent component : components)
		{
			if (component instanceof ClientTextTooltip)
			{
				RecomposerSink recomposer = new RecomposerSink();
				((ClientTextTooltip)component).text.accept(recomposer);
				recomposedLines.add(recomposer.getFormattedText());
			}
		}
		return recomposedLines;
	}
	
	private static class RecomposerSink implements FormattedCharSink
	{
		private StringBuilder builder = new StringBuilder();
		private MutableComponent text = new TextComponent("").withStyle(Style.EMPTY);

		@Override
		public boolean accept(int index, Style style, int charCode)
		{
			builder.append(Character.toChars(charCode));

			if (!style.equals(text.getStyle()))
			{
				text.append(new TextComponent(builder.toString()).withStyle(style));
				builder.setLength(0);
			}
			return true;
		}

		public FormattedText getFormattedText()
		{
			text.append(new TextComponent(builder.toString()).withStyle(text.getStyle()));
			return text;
		}
	}
}