| 1 | package net.minecraft.server.dialog.input;
|
| 2 |
|
| 3 | import com.mojang.serialization.Codec;
|
| 4 | import com.mojang.serialization.DataResult;
|
| 5 | import com.mojang.serialization.MapCodec;
|
| 6 | import com.mojang.serialization.codecs.RecordCodecBuilder;
|
| 7 | import java.util.List;
|
| 8 | import java.util.Optional;
|
| 9 | import net.minecraft.network.chat.Component;
|
| 10 | import net.minecraft.network.chat.ComponentSerialization;
|
| 11 | import net.minecraft.server.dialog.Dialog;
|
| 12 | import net.minecraft.util.ExtraCodecs;
|
| 13 |
|
| 14 | public record SingleOptionInput(int width, List<SingleOptionInput.Entry> entries, Component label, boolean labelVisible) implements InputControl {
|
| 15 | public static final MapCodec<SingleOptionInput> MAP_CODEC = RecordCodecBuilder.<SingleOptionInput>mapCodec(
|
| 16 | i -> i.group(
|
| 17 | Dialog.WIDTH_CODEC.optionalFieldOf("width", 200).forGetter(SingleOptionInput::width),
|
| 18 | ExtraCodecs.nonEmptyList(SingleOptionInput.Entry.CODEC.listOf()).fieldOf("options").forGetter(SingleOptionInput::entries),
|
| 19 | ComponentSerialization.CODEC.fieldOf("label").forGetter(SingleOptionInput::label),
|
| 20 | Codec.BOOL.optionalFieldOf("label_visible", true).forGetter(SingleOptionInput::labelVisible)
|
| 21 | )
|
| 22 | .apply(i, SingleOptionInput::new)
|
| 23 | )
|
| 24 | .validate(o -> {
|
| 25 | long initialCount = o.entries.stream().filter(SingleOptionInput.Entry::initial).count();
|
| 26 | return initialCount > 1L ? DataResult.error(() -> "Multiple initial values") : DataResult.success(o);
|
| 27 | });
|
| 28 |
|
| 29 | @Override
|
| 30 | public MapCodec<SingleOptionInput> mapCodec() {
|
| 31 | return MAP_CODEC;
|
| 32 | }
|
| 33 |
|
| 34 | public Optional<SingleOptionInput.Entry> initial() {
|
| 35 | return this.entries.stream().filter(SingleOptionInput.Entry::initial).findFirst();
|
| 36 | }
|
| 37 |
|
| 38 | public record Entry(String id, Optional<Component> display, boolean initial) {
|
| 39 | public static final Codec<SingleOptionInput.Entry> FULL_CODEC = RecordCodecBuilder.create(
|
| 40 | i -> i.group(
|
| 41 | Codec.STRING.fieldOf("id").forGetter(SingleOptionInput.Entry::id),
|
| 42 | ComponentSerialization.CODEC.optionalFieldOf("display").forGetter(SingleOptionInput.Entry::display),
|
| 43 | Codec.BOOL.optionalFieldOf("initial", false).forGetter(SingleOptionInput.Entry::initial)
|
| 44 | )
|
| 45 | .apply(i, SingleOptionInput.Entry::new)
|
| 46 | );
|
| 47 | public static final Codec<SingleOptionInput.Entry> CODEC = Codec.withAlternative(
|
| 48 | FULL_CODEC, Codec.STRING, id -> new SingleOptionInput.Entry(id, Optional.empty(), false)
|
| 49 | );
|
| 50 |
|
| 51 | public Component displayOrDefault() {
|
| 52 | return this.display.orElseGet(() -> Component.literal(this.id));
|
| 53 | }
|
| 54 | }
|
| 55 | }
|
| 56 |
|