|
3 | 3 | import com.google.gson.Gson;
|
4 | 4 | import com.google.gson.JsonObject;
|
5 | 5 | import com.google.gson.JsonParseException;
|
| 6 | +import com.mojang.datafixers.util.Either; |
6 | 7 | import com.mojang.serialization.Codec;
|
7 | 8 | import com.mojang.serialization.DataResult;
|
8 | 9 | import com.mojang.serialization.JsonOps;
|
|
24 | 25 | import java.util.HexFormat;
|
25 | 26 | import java.util.List;
|
26 | 27 | import java.util.Map;
|
27 |
| -import java.util.function.Function; |
28 | 28 | import java.util.regex.Pattern;
|
29 | 29 |
|
30 | 30 | public class ColorManager extends SinglePreparationResourceReloader<Map<Identifier, List<JsonObject>>> {
|
@@ -100,17 +100,22 @@ private static DataResult<Integer> parseHexColor(String str) {
|
100 | 100 | });
|
101 | 101 | }
|
102 | 102 |
|
| 103 | + private static String writeHexColor(int color) { |
| 104 | + var hex = HexFormat.of().withUpperCase().toHexDigits(color); |
| 105 | + return '#' + (hex.startsWith("00") ? hex.substring(2) : hex); |
| 106 | + } |
| 107 | + |
103 | 108 | public record ColorPair(int bg, int fg) {
|
104 | 109 | private static final int DEFAULT_FG = Colors.SCREEN_TEXT;
|
105 | 110 |
|
106 | 111 | private static final Codec<Integer> COLOR_CODEC =
|
107 |
| - Codec.STRING.comapFlatMap(ColorManager::parseHexColor, color -> '#' + HexFormat.of().withUpperCase().toHexDigits(color)); |
108 |
| - public static final Codec<ColorPair> CODEC = Codec.withAlternative( |
| 112 | + Codec.STRING.comapFlatMap(ColorManager::parseHexColor, ColorManager::writeHexColor); |
| 113 | + public static final Codec<ColorPair> CODEC = Codec.<ColorPair, ColorPair>either( |
109 | 114 | RecordCodecBuilder.create(instance -> instance.group(
|
110 | 115 | COLOR_CODEC.fieldOf("bg").forGetter(ColorPair::bg),
|
111 |
| - COLOR_CODEC.optionalFieldOf("fg", DEFAULT_FG).forGetter(ColorPair::bg) |
| 116 | + COLOR_CODEC.optionalFieldOf("fg", DEFAULT_FG).forGetter(ColorPair::fg) |
112 | 117 | ).apply(instance, ColorPair::new)),
|
113 | 118 | COLOR_CODEC.xmap(bg -> new ColorPair(bg, DEFAULT_FG), ColorPair::bg)
|
114 |
| - ); |
| 119 | + ).xmap(Either::unwrap, pair -> pair.fg == DEFAULT_FG ? Either.right(pair) : Either.left(pair)); |
115 | 120 | }
|
116 | 121 | }
|
0 commit comments