/
ExpandNewLineTextAcceptor.java
75 lines (69 loc) · 2.64 KB
/
ExpandNewLineTextAcceptor.java
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package mezz.jei.util;
import net.minecraft.util.text.IFormattableTextComponent;
import net.minecraft.util.text.ITextProperties;
import net.minecraft.util.text.StringTextComponent;
import net.minecraft.util.text.Style;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
public class ExpandNewLineTextAcceptor implements ITextProperties.IStyledTextAcceptor<Void> {
private final List<ITextProperties> lines = new ArrayList<>();
@Nullable
private IFormattableTextComponent lastComponent;
@Override
public Optional<Void> accept(Style style, String line) {
String[] descriptionLineExpanded = line.split("\\\\n");
for (int i = 0; i < descriptionLineExpanded.length; i++) {
String s = descriptionLineExpanded[i];
if (s.isEmpty()) {
//If the string is empty
if (i == 0 && lastComponent != null) {
// and we are the first string (for example from a string \nTest)
// and we had a last component (we are a variable in a translation string)
// add our last component as is and reset it
lines.add(lastComponent);
lastComponent = null;
} else {
//Otherwise just add the empty line
lines.add(StringTextComponent.EMPTY);
}
continue;
}
StringTextComponent textComponent = new StringTextComponent(s);
textComponent.setStyle(style);
if (lastComponent != null) {
//If we already have a component that we want to continue with
if (i == 0) {
// and we are the first line, add ourselves to the last component
if (!lastComponent.getStyle().isEmpty() && !lastComponent.getStyle().equals(style)) {
//If it has a style and the style is different from the style the text component
// we are adding has add the last component as a sibling to an empty unstyled
// component so that we don't cause the styling to leak into the component we are adding
lastComponent = new StringTextComponent("").append(lastComponent);
}
lastComponent.append(textComponent);
continue;
} else {
// otherwise if we aren't the first line, add the old component to our list of lines
lines.add(lastComponent);
lastComponent = null;
}
}
if (i == descriptionLineExpanded.length - 1) {
//If we are the last line we are adding, persist the text component
lastComponent = textComponent;
} else {
//Otherwise add it to our list of lines
lines.add(textComponent);
}
}
return Optional.empty();
}
public void addLinesTo(List<ITextProperties> descriptionLinesExpanded) {
descriptionLinesExpanded.addAll(lines);
if (lastComponent != null) {
descriptionLinesExpanded.add(lastComponent);
}
}
}