| 1 | package net.minecraft.commands.arguments;
|
| 2 |
|
| 3 | import com.google.gson.JsonPrimitive;
|
| 4 | import com.mojang.brigadier.StringReader;
|
| 5 | import com.mojang.brigadier.arguments.ArgumentType;
|
| 6 | import com.mojang.brigadier.context.CommandContext;
|
| 7 | import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
| 8 | import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
|
| 9 | import com.mojang.brigadier.suggestion.Suggestions;
|
| 10 | import com.mojang.brigadier.suggestion.SuggestionsBuilder;
|
| 11 | import com.mojang.serialization.Codec;
|
| 12 | import com.mojang.serialization.JsonOps;
|
| 13 | import java.util.Arrays;
|
| 14 | import java.util.Collection;
|
| 15 | import java.util.concurrent.CompletableFuture;
|
| 16 | import java.util.function.Supplier;
|
| 17 | import java.util.stream.Collectors;
|
| 18 | import net.minecraft.commands.SharedSuggestionProvider;
|
| 19 | import net.minecraft.network.chat.Component;
|
| 20 | import net.minecraft.util.StringRepresentable;
|
| 21 |
|
| 22 | public class StringRepresentableArgument<T extends Enum<T> & StringRepresentable> implements ArgumentType<T> {
|
| 23 | private static final DynamicCommandExceptionType ERROR_INVALID_VALUE = new DynamicCommandExceptionType(
|
| 24 | value -> Component.translatableEscape("argument.enum.invalid", value)
|
| 25 | );
|
| 26 | private final Codec<T> codec;
|
| 27 | private final Supplier<T[]> values;
|
| 28 |
|
| 29 | protected StringRepresentableArgument(final Codec<T> codec, final Supplier<T[]> values) {
|
| 30 | this.codec = codec;
|
| 31 | this.values = values;
|
| 32 | }
|
| 33 |
|
| 34 | public T parse(final StringReader reader) throws CommandSyntaxException {
|
| 35 | String id = reader.readUnquotedString();
|
| 36 | return this.codec.parse(JsonOps.INSTANCE, new JsonPrimitive(id)).result().orElseThrow(() -> ERROR_INVALID_VALUE.createWithContext(reader, id));
|
| 37 | }
|
| 38 |
|
| 39 | @Override
|
| 40 | public <S> CompletableFuture<Suggestions> listSuggestions(final CommandContext<S> context, final SuggestionsBuilder builder) {
|
| 41 | return SharedSuggestionProvider.suggest(
|
| 42 | Arrays.<Enum>stream((Enum[])this.values.get())
|
| 43 | .map(rec$ -> ((StringRepresentable)rec$).getSerializedName())
|
| 44 | .map(this::convertId)
|
| 45 | .collect(Collectors.toList()),
|
| 46 | builder
|
| 47 | );
|
| 48 | }
|
| 49 |
|
| 50 | @Override
|
| 51 | public Collection<String> getExamples() {
|
| 52 | return Arrays.<Enum>stream((Enum[])this.values.get())
|
| 53 | .map(rec$ -> ((StringRepresentable)rec$).getSerializedName())
|
| 54 | .map(this::convertId)
|
| 55 | .limit(2L)
|
| 56 | .collect(Collectors.toList());
|
| 57 | }
|
| 58 |
|
| 59 | protected String convertId(final String id) {
|
| 60 | return id;
|
| 61 | }
|
| 62 | }
|
| 63 |
|