Add HoverEventSource to ItemStack

This commit is contained in:
TheMode 2021-04-10 17:01:50 +02:00
parent d2efb43625
commit bd3c678bde
3 changed files with 22 additions and 4 deletions

View File

@ -10,12 +10,12 @@ import net.minestom.server.entity.EntityType;
import net.minestom.server.item.ItemStack;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jglrxavpok.hephaistos.nbt.NBTCompound;
import java.util.UUID;
/**
* Represents a hover event for a specific portion of the message.
*
* @deprecated Use {@link HoverEvent}
*/
@Deprecated
@ -93,8 +93,8 @@ public class ChatHoverEvent {
JsonObject obj = GsonComponentSerializer.gson().serializer().toJsonTree(Component.empty().hoverEvent(event)).getAsJsonObject();
obj = obj.get("hoverEvent").getAsJsonObject().get("contents").getAsJsonObject();
NBTCompound compound = itemStack.getMeta().toNBT();
obj.add("tag", new JsonPrimitive(compound.toSNBT()));
final String snbt = itemStack.getMeta().toSNBT();
obj.add("tag", new JsonPrimitive(snbt));
return new ChatHoverEvent("show_item", obj);
}

View File

@ -30,6 +30,7 @@ public class ItemMeta implements Writeable {
private final NBTCompound nbt;
private final ItemMetaBuilder emptyBuilder;
private String cachedSNBT;
private BinaryWriter cachedBuffer;
protected ItemMeta(@NotNull ItemMetaBuilder metaBuilder) {
@ -110,6 +111,13 @@ public class ItemMeta implements Writeable {
return nbt.deepClone();
}
public @NotNull String toSNBT() {
if (cachedSNBT == null) {
this.cachedSNBT = nbt.toSNBT();
}
return cachedSNBT;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;

View File

@ -1,7 +1,10 @@
package net.minestom.server.item;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.event.HoverEvent;
import net.kyori.adventure.text.event.HoverEventSource;
import net.minestom.server.item.rule.VanillaStackingRule;
import net.minestom.server.utils.NBTUtils;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@ -18,7 +21,7 @@ import java.util.function.UnaryOperator;
* <p>
* An item stack cannot be null, {@link ItemStack#AIR} should be used instead.
*/
public class ItemStack {
public class ItemStack implements HoverEventSource<HoverEvent.ShowItem> {
/**
* Constant AIR item. Should be used instead of 'null'.
@ -194,4 +197,11 @@ public class ItemStack {
return new ItemStackBuilder(material, meta.builder(), store.builder())
.amount(amount);
}
@Override
public @NotNull HoverEvent<HoverEvent.ShowItem> asHoverEvent(@NotNull UnaryOperator<HoverEvent.ShowItem> op) {
return HoverEvent.showItem(op.apply(HoverEvent.ShowItem.of(this.material,
this.amount,
NBTUtils.asBinaryTagHolder(this.meta.toNBT().getCompound("tag")))));
}
}