Add dynamic item properties and visual interaction editor

This commit is contained in:
2026-09-08 17:56:58 +03:00
parent e1328e5c51
commit 78ada25dae
25 changed files with 1254 additions and 74 deletions
@@ -1,16 +1,22 @@
package online.astradev.plus.editor.client;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.stream.StreamSupport;
import com.google.gson.JsonObject;
import com.google.gson.JsonElement;
import com.google.gson.JsonNull;
public final class EditorCatalog {
private JsonObject catalogs = new JsonObject();
private final Map<String, JsonObject> materials = new HashMap<>();
public void update(JsonObject response) {
if (response.has("catalogs") && response.get("catalogs").isJsonObject())
catalogs = response.getAsJsonObject("catalogs").deepCopy();
if (response.has("componentExamples")) catalogs.add("componentExamples", response.get("componentExamples").deepCopy());
}
public List<String> values(String name) {
@@ -18,4 +24,23 @@ public final class EditorCatalog {
return StreamSupport.stream(catalogs.getAsJsonArray(name).spliterator(), false)
.map(value -> value.getAsString()).toList();
}
public void material(JsonObject response) {
if (response.has("id") && response.has("components") && response.get("components").isJsonObject())
materials.put(response.get("id").getAsString(), response.deepCopy());
}
public boolean hasMaterial(String id) { return materials.containsKey(id); }
public JsonObject defaults(String id) {
var material = materials.get(id);
return material == null ? new JsonObject() : material.getAsJsonObject("components").deepCopy();
}
public JsonElement example(String id) {
for (String key : List.of("componentExamples", "examples")) {
if (catalogs.has(key) && catalogs.get(key).isJsonObject() && catalogs.getAsJsonObject(key).has(id))
return catalogs.getAsJsonObject(key).get(id).deepCopy();
}
return JsonNull.INSTANCE;
}
}
@@ -0,0 +1,37 @@
package online.astradev.plus.editor.client;
import net.minecraft.client.Minecraft;
import net.minecraft.core.component.DataComponents;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.resources.Identifier;
import net.minecraft.world.item.ItemStack;
import online.astradev.plus.editor.form.ContentDraft;
/** Uses the local vanilla name and an installed resource-pack model when one is available. */
public final class ItemPreview {
private ItemPreview() {}
public static ItemStack base(ContentDraft draft) {
if (Minecraft.getInstance().level == null) return ItemStack.EMPTY;
var id = Identifier.tryParse(draft.text("minecraft:paper", "material"));
return id == null ? ItemStack.EMPTY : BuiltInRegistries.ITEM.getOptional(id).map(ItemStack::new).orElse(ItemStack.EMPTY);
}
public static String name(ContentDraft draft) {
var stack = base(draft);
if (!stack.isEmpty()) return stack.getHoverName().getString();
var id = Identifier.tryParse(draft.text("minecraft:paper", "material"));
return id == null ? "Неизвестный предмет" : BuiltInRegistries.ITEM.getOptional(id)
.map(item -> net.minecraft.network.chat.Component.translatable(item.getDescriptionId()).getString()).orElse("Неизвестный предмет");
}
public static ItemStack visual(ContentDraft draft) {
var stack = base(draft);
var model = Identifier.tryParse(draft.id());
if (!stack.isEmpty() && model != null) {
var definition = Identifier.fromNamespaceAndPath(model.getNamespace(), "items/" + model.getPath() + ".json");
if (Minecraft.getInstance().getResourceManager().getResource(definition).isPresent()) stack.set(DataComponents.ITEM_MODEL, model);
}
return stack;
}
}
@@ -15,6 +15,7 @@ public final class ComponentExamples {
case "minecraft:enchantments", "minecraft:stored_enchantments" -> "{\"minecraft:unbreaking\":3}";
case "minecraft:food" -> "{\"nutrition\":6,\"saturation\":7.2,\"can_always_eat\":false}";
case "minecraft:consumable" -> "{\"consume_seconds\":1.6,\"animation\":\"eat\"}";
case "minecraft:death_protection" -> "{\"death_effects\":[{\"type\":\"minecraft:clear_all_effects\"},{\"type\":\"minecraft:apply_effects\",\"effects\":[{\"id\":\"minecraft:regeneration\",\"duration\":900,\"amplifier\":1},{\"id\":\"minecraft:absorption\",\"duration\":100,\"amplifier\":1},{\"id\":\"minecraft:fire_resistance\",\"duration\":800}]}]}";
case "minecraft:tool" -> "{\"rules\":[{\"blocks\":\"#minecraft:mineable/pickaxe\",\"speed\":8.0,\"correct_for_drops\":true}],\"default_mining_speed\":1.0,\"damage_per_block\":1,\"can_destroy_blocks_in_creative\":true}";
case "minecraft:attribute_modifiers" -> "[{\"type\":\"minecraft:attack_damage\",\"id\":\"astraplus:damage\",\"amount\":5.0,\"operation\":\"add_value\",\"slot\":\"mainhand\"}]";
case "minecraft:lore" -> "[\"Описание предмета\"]";
@@ -0,0 +1,43 @@
package online.astradev.plus.editor.form;
import java.util.Arrays;
import java.util.List;
import com.google.gson.JsonArray;
/** Typed field helpers work on a local document without removing unrelated keys. */
public final class DataFields {
private DataFields() {}
public static FormField text(ContentDraft local, String label, String hint, String fallback, List<String> choices, String... path) {
return new FormField(String.join("/", path), label, hint, () -> local.text(fallback, path), value -> local.string(value.trim(), path), choices, false);
}
public static FormField number(ContentDraft local, String label, String hint, String fallback, boolean integer, double min, double max, String... path) {
return FormField.text(String.join("/", path), label, hint, () -> local.text(fallback, path), value -> {
if (value.isBlank()) throw new IllegalArgumentException("Введите значение или верните значение по умолчанию.");
local.number(value, integer, min, max, path);
});
}
public static FormField bool(ContentDraft local, String label, boolean fallback, String... path) {
return new FormField(String.join("/", path), label, "Включить или выключить свойство.",
() -> local.text(Boolean.toString(fallback), path).equals("true") ? "Да" : "Нет",
value -> local.bool(value.equals("Да"), path), List.of("Нет", "Да"), true);
}
public static FormField choice(ContentDraft local, String label, String hint, String fallback, List<String> values, String... path) {
return new FormField(String.join("/", path), label, hint, () -> local.text(fallback, path), value -> local.string(value, path), values, true);
}
public static FormField identifiers(ContentDraft local, String label, String hint, List<String> choices, String... path) {
return new FormField(String.join("/", path), label, hint, () -> {
var value = local.get(path);
if (!value.isJsonArray()) return "";
return java.util.stream.StreamSupport.stream(value.getAsJsonArray().spliterator(), false)
.map(element -> element.getAsString()).collect(java.util.stream.Collectors.joining(", "));
}, value -> {
var array = new JsonArray();
Arrays.stream(value.split(",")).map(String::trim).filter(id -> !id.isEmpty()).forEach(id -> {
if (!id.matches("[a-z0-9_.-]+:[a-z0-9_./-]+")) throw new IllegalArgumentException("Нужны идентификаторы namespace:путь через запятую.");
array.add(id);
});
local.set(array, path);
}, choices, false);
}
}
@@ -0,0 +1,53 @@
package online.astradev.plus.editor.form;
import java.util.Map;
import com.google.gson.JsonObject;
/** Human-readable effect summaries shared by forms and list rows. */
public final class EffectNames {
private static final Map<String, String> NAMES = Map.ofEntries(
Map.entry("regeneration", "Регенерация"), Map.entry("absorption", "Поглощение"), Map.entry("fire_resistance", "Огнестойкость"),
Map.entry("speed", "Скорость"), Map.entry("slowness", "Замедление"), Map.entry("haste", "Спешка"),
Map.entry("mining_fatigue", "Усталость"), Map.entry("strength", "Сила"), Map.entry("instant_health", "Исцеление"),
Map.entry("instant_damage", "Моментальный урон"), Map.entry("jump_boost", "Прыгучесть"), Map.entry("nausea", "Тошнота"),
Map.entry("resistance", "Сопротивление"), Map.entry("water_breathing", "Подводное дыхание"), Map.entry("invisibility", "Невидимость"),
Map.entry("blindness", "Слепота"), Map.entry("night_vision", "Ночное зрение"), Map.entry("hunger", "Голод"),
Map.entry("weakness", "Слабость"), Map.entry("poison", "Отравление"), Map.entry("wither", "Иссушение"),
Map.entry("health_boost", "Прилив здоровья"), Map.entry("saturation", "Насыщение"), Map.entry("glowing", "Свечение"),
Map.entry("levitation", "Левитация"), Map.entry("luck", "Удача"), Map.entry("unluck", "Невезение"),
Map.entry("slow_falling", "Плавное падение"), Map.entry("conduit_power", "Морская сила"), Map.entry("dolphins_grace", "Грация дельфина"),
Map.entry("bad_omen", "Дурное знамение"), Map.entry("hero_of_the_village", "Герой деревни"), Map.entry("darkness", "Тьма"));
private EffectNames() {}
public static String label(String id) {
return id.startsWith("minecraft:") ? NAMES.getOrDefault(id.substring(10), id.substring(10).replace('_', ' ')) : id;
}
public static String effect(JsonObject value) {
var local = new ContentDraft(value, "display");
String level = local.text("0", "amplifier");
String duration = local.text("0", "duration");
try {
int amplifier = Integer.parseInt(level) + 1;
return label(local.text("", "id")) + " " + amplifier + ", " + (duration.equals("-1") ? "без ограничения"
: new java.math.BigDecimal(duration).divide(java.math.BigDecimal.valueOf(20)).stripTrailingZeros().toPlainString() + " с");
} catch (NumberFormatException error) { return label(local.text("", "id")); }
}
public static String action(JsonObject value) {
var local = new ContentDraft(value, "display");
return switch (local.text("", "type")) {
case "minecraft:clear_all_effects" -> "Снять все эффекты";
case "minecraft:apply_effects" -> {
var effects = local.get("effects");
String names = effects.isJsonArray() ? java.util.stream.StreamSupport.stream(effects.getAsJsonArray().spliterator(), false)
.filter(element -> element.isJsonObject()).map(element -> effect(element.getAsJsonObject())).collect(java.util.stream.Collectors.joining("; ")) : "";
yield "Наложить эффекты: " + (names.isBlank() ? "список пуст" : names);
}
case "minecraft:remove_effects" -> "Снять выбранные эффекты";
case "minecraft:teleport_randomly" -> "Случайное перемещение";
case "minecraft:play_sound" -> "Воспроизвести звук";
default -> "Особое действие";
};
}
}
@@ -0,0 +1,128 @@
package online.astradev.plus.editor.form;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import online.astradev.plus.editor.client.EditorCatalog;
/** Separates inherited values from explicit patches; opening a property never creates an override. */
public final class PropertyModel {
public static final Set<String> MANAGED = Set.of("minecraft:custom_data", "minecraft:item_model", "minecraft:item_name", "minecraft:block_state", "minecraft:block_entity_data");
private static final Map<String, String> NAMES = Map.ofEntries(
Map.entry("max_damage", "Прочность"), Map.entry("damage", "Текущее повреждение"), Map.entry("max_stack_size", "Размер стопки"),
Map.entry("repair_cost", "Стоимость предыдущего ремонта"),
Map.entry("food", "Питание"), Map.entry("consumable", "Употребление и эффекты"), Map.entry("death_protection", "Спасение от смерти"),
Map.entry("damage_resistant", "Защита предмета от урона"), Map.entry("unbreakable", "Неразрушимость"),
Map.entry("enchantments", "Наложенные зачарования"), Map.entry("stored_enchantments", "Зачарования книги"),
Map.entry("enchantable", "Зачаровываемость"), Map.entry("attribute_modifiers", "Характеристики"), Map.entry("tool", "Добыча блоков"),
Map.entry("lore", "Описание"), Map.entry("potion_contents", "Содержимое зелья"), Map.entry("equippable", "Надевание"),
Map.entry("enchantment_glint_override", "Блеск зачарования"), Map.entry("repairable", "Материалы ремонта"),
Map.entry("use_remainder", "Предмет после использования"), Map.entry("use_cooldown", "Задержка использования"),
Map.entry("break_sound", "Звук поломки"), Map.entry("rarity", "Редкость"), Map.entry("swing_animation", "Анимация взмаха"),
Map.entry("tooltip_display", "Содержимое подсказки"), Map.entry("tooltip_style", "Оформление подсказки"),
Map.entry("custom_name", "Пользовательское имя"), Map.entry("custom_model_data", "Параметры модели"),
Map.entry("creative_slot_lock", "Фиксация в творческом инвентаре"), Map.entry("intangible_projectile", "Призрачный снаряд"),
Map.entry("use_effects", "Эффекты использования"), Map.entry("minimum_attack_charge", "Минимальный заряд атаки"),
Map.entry("damage_type", "Тип наносимого урона"), Map.entry("can_place_on", "Допустимые блоки для установки"),
Map.entry("can_break", "Допустимые блоки для разрушения"), Map.entry("weapon", "Оружие"),
Map.entry("attack_range", "Дальность атаки"), Map.entry("glider", "Планирование"),
Map.entry("blocks_attacks", "Блокирование атак"), Map.entry("piercing_weapon", "Прокалывающая атака"),
Map.entry("kinetic_weapon", "Атака с разгона"), Map.entry("additional_trade_cost", "Доплата при торговле"),
Map.entry("dye", "Краситель"), Map.entry("dyed_color", "Цвет окраски"), Map.entry("map_color", "Цвет карты"),
Map.entry("map_id", "Номер карты"), Map.entry("map_decorations", "Отметки на карте"), Map.entry("map_post_processing", "Обработка карты"),
Map.entry("charged_projectiles", "Заряженные снаряды"), Map.entry("bundle_contents", "Содержимое мешка"),
Map.entry("potion_duration_scale", "Множитель длительности зелья"), Map.entry("suspicious_stew_effects", "Эффекты подозрительного супа"),
Map.entry("writable_book_content", "Содержимое редактируемой книги"), Map.entry("written_book_content", "Содержимое подписанной книги"),
Map.entry("trim", "Отделка брони"), Map.entry("debug_stick_state", "Состояние палочки отладки"),
Map.entry("entity_data", "Данные сущности"), Map.entry("bucket_entity_data", "Сущность в ведре"),
Map.entry("instrument", "Музыкальный инструмент"), Map.entry("provides_trim_material", "Материал отделки"),
Map.entry("ominous_bottle_amplifier", "Уровень зловещего эффекта"), Map.entry("jukebox_playable", "Запись для проигрывателя"),
Map.entry("provides_banner_patterns", "Доступные узоры знамени"), Map.entry("recipes", "Открываемые рецепты"),
Map.entry("lodestone_tracker", "Цель компаса"), Map.entry("firework_explosion", "Взрыв фейерверка"),
Map.entry("fireworks", "Ракета фейерверка"), Map.entry("profile", "Профиль головы"),
Map.entry("note_block_sound", "Звук нотного блока"), Map.entry("banner_patterns", "Узоры знамени"),
Map.entry("base_color", "Основной цвет"), Map.entry("pot_decorations", "Узор глиняного горшка"),
Map.entry("container", "Содержимое контейнера"), Map.entry("bees", "Пчёлы внутри"),
Map.entry("sulfur_cube_content", "Содержимое серного куба"), Map.entry("lock", "Замок контейнера"),
Map.entry("container_loot", "Добыча контейнера"));
private static final Map<String, String> ENTITY_NAMES = Map.ofEntries(
Map.entry("villager", "жителя"), Map.entry("wolf", "волка"), Map.entry("fox", "лисы"), Map.entry("salmon", "лосося"),
Map.entry("parrot", "попугая"), Map.entry("tropical_fish", "тропической рыбы"), Map.entry("mooshroom", "грибной коровы"),
Map.entry("rabbit", "кролика"), Map.entry("pig", "свиньи"), Map.entry("cow", "коровы"), Map.entry("chicken", "курицы"),
Map.entry("zombie_nautilus", "зомби-наутилуса"), Map.entry("frog", "лягушки"), Map.entry("horse", "лошади"),
Map.entry("painting", "картины"), Map.entry("llama", "ламы"), Map.entry("axolotl", "аксолотля"),
Map.entry("cat", "кошки"), Map.entry("sheep", "овцы"), Map.entry("shulker", "шалкера"));
private final ContentDraft draft;
private final EditorCatalog catalog;
public PropertyModel(ContentDraft draft, EditorCatalog catalog) { this.draft = draft; this.catalog = catalog; }
public static String label(String id) {
String path = id.substring(id.indexOf(':') + 1);
if (NAMES.containsKey(path)) return NAMES.get(path);
String[] parts = path.split("/", 2);
if (parts.length == 2 && ENTITY_NAMES.containsKey(parts[0])) {
String property = switch (parts[1]) {
case "variant" -> "Разновидность"; case "sound_variant" -> "Звуки"; case "collar" -> "Ошейник";
case "size" -> "Размер"; case "color", "base_color" -> "Цвет"; case "pattern" -> "Узор"; case "pattern_color" -> "Цвет узора"; default -> parts[1];
};
return property + " " + ENTITY_NAMES.get(parts[0]);
}
String words = path.replace('_', ' ').replace('/', ':');
return words.isEmpty() ? id : Character.toUpperCase(words.charAt(0)) + words.substring(1);
}
public JsonObject inherited() { return catalog.defaults(draft.text("minecraft:paper", "material")); }
public List<String> present() {
var names = new LinkedHashSet<>(inherited().keySet());
var patch = draft.get("components");
if (patch.isJsonObject()) patch.getAsJsonObject().keySet().forEach(id -> names.add(id.startsWith("!") ? id.substring(1) : id));
return names.stream().filter(id -> !MANAGED.contains(id)).sorted(java.util.Comparator.<String>comparingInt(id -> switch (state(id)) {
case "Добавлено" -> 0; case "Изменено" -> 1; case "Отключено" -> 2; default -> 3;
}).thenComparing(PropertyModel::label)).toList();
}
public String state(String id) {
if (!draft.get("components", "!" + id).isJsonNull()) return "Отключено";
if (!draft.get("components", id).isJsonNull()) return inherited().has(id) ? "Изменено" : "Добавлено";
return "Основа";
}
public JsonElement value(String id) {
var patch = draft.get("components", id);
if (!patch.isJsonNull()) return patch;
var inherited = inherited();
if (inherited.has(id)) return inherited.get(id).deepCopy();
var example = catalog.example(id);
return example.isJsonNull() ? JsonParser.parseString(ComponentExamples.value(id)) : example;
}
public String summary(String id) {
var value = value(id);
if (value.isJsonPrimitive()) {
if (id.equals("minecraft:rarity")) return switch (value.getAsString()) {
case "common" -> "Обычная"; case "uncommon" -> "Необычная"; case "rare" -> "Редкая"; case "epic" -> "Эпическая"; default -> "Настроенная редкость";
};
if (id.equals("minecraft:break_sound")) return "Звук при полном износе предмета";
if (value.getAsJsonPrimitive().isBoolean()) return value.getAsBoolean() ? "Включено" : "Выключено";
return "Значение: " + value.getAsString();
}
if (value.isJsonObject()) {
var local = new ContentDraft(value.getAsJsonObject(), "display");
return switch (id) {
case "minecraft:food" -> "Питание: " + local.text("0", "nutrition") + " Насыщение: " + local.text("0", "saturation");
case "minecraft:consumable" -> "Время: " + local.text("1.6", "consume_seconds") + " с Анимация: " + local.text("eat", "animation");
case "minecraft:damage_resistant" -> local.text("", "types").equals("#minecraft:is_fire")
? "Предмет не сгорает в огне и лаве" : "Защита от урона: " + local.text("Особый список", "types");
case "minecraft:enchantable" -> "Зачаровываемость: " + local.text("0", "value");
case "minecraft:unbreakable" -> "Прочность не расходуется";
case "minecraft:death_protection" -> "Спасение от смертельного урона и настраиваемые эффекты";
case "minecraft:tool" -> "Скорость: " + local.text("1", "default_mining_speed") + " Расход прочности: " + local.text("1", "damage_per_block");
default -> value.getAsJsonObject().isEmpty() ? "Свойство активно; используются параметры по умолчанию"
: "Настроенное свойство. Откройте для подробностей.";
};
}
return value.isJsonArray() ? "Элементов: " + value.getAsJsonArray().size() : "Свойство настроено";
}
}
@@ -0,0 +1,66 @@
package online.astradev.plus.editor.screen;
import java.util.List;
import com.google.gson.JsonObject;
import net.minecraft.client.Minecraft;
import online.astradev.plus.editor.client.EditorCatalog;
import online.astradev.plus.editor.form.ContentDraft;
import online.astradev.plus.editor.form.DataFields;
import online.astradev.plus.editor.form.FormField;
public final class BehaviorForms {
public static final java.util.Map<String, String> LABELS = java.util.Collections.unmodifiableMap(new java.util.LinkedHashMap<>(java.util.Map.of(
"fertilize", "Удобрение и урожай", "clearVegetation", "Очистка растительности", "absorbFluid", "Поглощение жидкости",
"wash", "Очистка в котле", "mobDrop", "Добыча с моба", "crafting", "Рецепт без формы")));
private BehaviorForms() {}
public static void open(BehaviorScreen parent, ContentDraft draft, EditorCatalog catalog, String key) {
JsonObject initial = ConditionForms.object(draft.get("behaviors", key));
List<SettingsScreen.Action> actions = key.equals("crafting") ? List.of(new SettingsScreen.Action("Ингредиенты",
(screen, local) -> Minecraft.getInstance().gui.setScreen(new IdentifierListScreen(screen, "Ингредиенты рецепта",
ConditionForms.array(local.get("ingredients")), java.util.stream.Stream.concat(catalog.values("items").stream(),
catalog.values("customItems").stream()).distinct().sorted().toList(), 9, true, value -> local.set(value, "ingredients"))))) : List.of();
Minecraft.getInstance().gui.setScreen(new SettingsScreen(parent, LABELS.get(key), initial, local -> fields(local, catalog, key),
value -> { draft.set(value, "behaviors", key); parent.changed(); }, actions, description(key)));
}
private static List<FormField> fields(ContentDraft d, EditorCatalog c, String key) {
return switch (key) {
case "fertilize" -> List.of(
number(d, "Радиус по горизонтали", "21", 0, 32, "radius"), number(d, "Радиус по вертикали", "2", 0, 8, "verticalRadius"),
number(d, "Множитель урожая", "3", 1, 16, "harvestMultiplier"), DataFields.bool(d, "Выращивать траву и цветы", true, "growGrass"));
case "clearVegetation" -> List.of(number(d, "Радиус по горизонтали", "7", 0, 32, "radius"),
number(d, "Радиус по вертикали", "2", 0, 8, "verticalRadius"));
case "absorbFluid" -> List.of(
DataFields.choice(d, "Жидкость", "Поглощаются только соединённые клетки этой жидкости.", "minecraft:lava", List.of("minecraft:lava", "minecraft:water"), "fluid"),
number(d, "Радиус поиска", "3", 1, 16, "radius"), number(d, "Предел поглощённых блоков", "4096", 1, 16384, "maxBlocks"),
DataFields.text(d, "Превратить в предмет / блок", "ID пользовательского определения. Для установленного блока результат также должен быть блоком.",
"", c.values("customItems"), "result"));
case "wash" -> List.of(DataFields.text(d, "Предмет после очистки", "ID пользовательского определения. Котёл должен содержать воду.",
"", c.values("customItems"), "result"));
case "mobDrop" -> List.of(DataFields.text(d, "Тип моба", "Ванильный тип сущности.", "minecraft:wither_skeleton", c.values("entities"), "entity"),
DataFields.number(d, "Вероятность", "0: никогда; 1: всегда.", "1", false, 0, 1, "chance"),
number(d, "Минимум предметов", "1", 0, 64, "minimum"), number(d, "Максимум предметов", "2", 0, 64, "maximum"),
number(d, "Добавка за уровень Добычи", "1", 0, 8, "extraPerLooting"));
case "crafting" -> List.of(number(d, "Количество в результате", "1", 1, 64, "count"),
DataFields.identifiers(d, "Ингредиенты", "1–9 ID через запятую; повторы означают несколько единиц. Есть визуальный список.", List.of(), "ingredients"));
default -> List.of();
};
}
private static FormField number(ContentDraft d, String label, String fallback, int min, int max, String key) {
return DataFields.number(d, label, "Допустимо от " + min + " до " + max + ".", fallback, true, min, max, key);
}
private static String description(String key) {
return switch (key) {
case "fertilize" -> "Расходует один предмет. Ускоряет рост; зрелые плоды получают множитель урожая. Семена не умножаются.";
case "clearVegetation" -> "Расходует один предмет после удаления растений. Культуры и деревья сохраняются.";
case "absorbFluid" -> "Установленный блок впитывает жидкость вокруг себя. Для обычного предмета используется ПКМ.";
case "wash" -> "ПКМ по котлу с водой: обмен одного предмета и расход одного уровня воды.";
case "mobDrop" -> "Дополнительная добыча при убийстве игроком. Условия взаимодействия к добыче не применяются.";
case "crafting" -> "Результат: этот предмет. Пользовательские ингредиенты проверяются по ID. Условия ПКМ к рецепту не применяются.";
default -> "";
};
}
}
@@ -0,0 +1,43 @@
package online.astradev.plus.editor.screen;
import java.util.List;
import net.minecraft.client.gui.GuiGraphicsExtractor;
import online.astradev.plus.editor.client.EditorCatalog;
import online.astradev.plus.editor.form.ContentDraft;
public final class BehaviorScreen extends EditorScreen {
private static final List<String> ORDER = List.of("fertilize", "clearVegetation", "absorbFluid", "wash", "mobDrop", "crafting");
private final ContentEditorScreen parent;
private final ContentDraft draft;
private final EditorCatalog catalog;
private String selected;
public BehaviorScreen(ContentEditorScreen parent, ContentDraft draft, EditorCatalog catalog) {
super("Взаимодействия и рецепты");
this.parent = parent; this.draft = draft; this.catalog = catalog;
}
@Override protected void init() {
var list = addRenderableWidget(new ChoiceList(minecraft, 12, 63, width - 24, Math.max(26, height - 164), label -> {
selected = ORDER.stream().filter(key -> label.endsWith(BehaviorForms.LABELS.get(key))).findFirst().orElseThrow();
rebuildWidgets();
}));
list.values(ORDER.stream().map(key -> (draft.get("behaviors", key).isJsonObject() ? "[Включено] " : "[Не добавлено] ") + BehaviorForms.LABELS.get(key)).toList());
int third = (width - 32) / 3;
button("Настроить", 12, height - 90, third, () -> BehaviorForms.open(this, draft, catalog, selected)).active = selected != null;
button("Отключить", 16 + third, height - 90, third, () -> { draft.set(null, "behaviors", selected); changed(); rebuildWidgets(); })
.active = selected != null && draft.get("behaviors", selected).isJsonObject();
button("Условия", 20 + third * 2, height - 90, third, () -> ConditionForms.open(this, catalog,
ConditionForms.object(draft.get("behaviors", "conditions")), value -> { draft.set(value, "behaviors", "conditions"); changed(); }));
button("Назад", 12, height - 27, 110, this::onClose);
button("Сценарии JavaScript", width - 191, height - 27, 179, () -> minecraft.gui.setScreen(new ScriptBindingsScreen(this, draft, catalog, parent::componentChanged)));
if (status.isBlank()) status("Выберите механику и настройте её. Комбинации проверяет сервер при сохранении определения.", false);
}
public void changed() { parent.componentChanged(); status("Настройки изменены в черновике. Примените их кнопкой «Сохранить» в определении.", false); }
@Override public void extractRenderState(GuiGraphicsExtractor g, int mouseX, int mouseY, float a) {
super.extractRenderState(g, mouseX, mouseY, a);
g.text(font, "Механики добавляются к любому предмету или блоку", 14, 43, 0xFFBDD2D8);
}
@Override public void onClose() { minecraft.gui.setScreen(parent); }
}
@@ -1,57 +1,88 @@
package online.astradev.plus.editor.screen;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.Locale;
import net.minecraft.client.gui.GuiGraphicsExtractor;
import net.minecraft.client.gui.components.EditBox;
import net.minecraft.network.chat.Component;
import online.astradev.plus.editor.client.EditorCatalog;
import online.astradev.plus.editor.client.ItemPreview;
import online.astradev.plus.editor.form.ContentDraft;
import online.astradev.plus.editor.form.PropertyModel;
public final class ComponentListScreen extends EditorScreen {
private static final Set<String> RESERVED = Set.of("minecraft:custom_data", "minecraft:item_model", "minecraft:item_name",
"minecraft:block_state", "minecraft:block_entity_data");
private final ContentEditorScreen parent;
private final ContentDraft draft;
private final EditorCatalog catalog;
private final PropertyModel properties;
private String selected;
private String query = "";
private String pending;
private final java.util.List<net.minecraft.client.gui.components.Button> actions = new java.util.ArrayList<>();
public ComponentListScreen(ContentEditorScreen parent, ContentDraft draft, EditorCatalog catalog) {
super("AstraPlus: компоненты предмета");
super("Свойства предмета");
this.parent = parent;
this.draft = draft;
this.catalog = catalog;
this.properties = new PropertyModel(draft, catalog);
}
@Override protected void init() {
var components = draft.get("components");
var names = new LinkedHashSet<String>();
if (components.isJsonObject()) components.getAsJsonObject().keySet().stream().sorted()
.forEach(key -> names.add(key.startsWith("!") ? key.substring(1) : key));
var list = addRenderableWidget(new ChoiceList(minecraft, 12, 38, width - 24, Math.max(30, height - 118), this::open));
list.values(names.stream().toList());
button("Добавить компонент", 12, height - 27, Math.min(170, width / 2), () -> {
List<String> available = catalog.values("components").stream().filter(id -> !RESERVED.contains(id)).toList();
minecraft.gui.setScreen(new ChoiceScreen(this, "Выберите компонент", available, this::scheduleOpen));
});
button("Назад", width - 102, height - 27, 90, this::onClose);
status("Выберите переопределение. Сложные свойства редактируются отдельно в JSON; остальные поля сохраняются.", false);
actions.clear();
var list = addRenderableWidget(new PropertyList(minecraft, 12, 90, width - 24, Math.max(30, height - 192), properties,
id -> { selected = id; actions.forEach(button -> button.active = true); status(PropertyModel.label(id) + ": " + properties.state(id) + ". Выберите действие ниже.", false); }));
var search = addRenderableWidget(new EditBox(font, 18, 61, width - 36, 20, Component.literal("Поиск свойства")));
search.setValue(query);
search.setHint(Component.literal("Поиск по названию или идентификатору"));
search.setResponder(value -> { query = value; list.values(filtered()); });
list.values(filtered());
if (selected != null) list.select(selected);
int part = (width - 48) / 4;
actions.add(button("Изменить", 18, height - 94, part, () -> { if (selected != null) open(selected); }));
actions.add(button("Наследовать", 22 + part, height - 94, part, "Вернуть исходное свойство ванильной основы.", () -> reset(false)));
actions.add(button("Отключить", 26 + part * 2, height - 94, part, "Удалить свойство у этого определения, включая наследуемое.", () -> reset(true)));
actions.add(button("JSON…", 30 + part * 3, height - 94, part, "Полный формат любого поддерживаемого компонента.", () -> {
if (selected != null) minecraft.gui.setScreen(new ComponentValueScreen(this, parent, draft, selected));
}));
actions.forEach(button -> button.active = selected != null);
button("+ Добавить свойство", width - 174, 36, 156, () -> minecraft.gui.setScreen(new ChoiceScreen(this,
"Все поддерживаемые свойства", catalog.values("components").stream().filter(id -> !PropertyModel.MANAGED.contains(id))
.map(id -> PropertyModel.label(id).equals(id) ? id : PropertyModel.label(id) + " [" + id + "]").sorted().toList(), value -> {
pending = value.endsWith("]") ? value.substring(value.lastIndexOf('[') + 1, value.length() - 1) : value;
})));
button("Назад", width - 118, height - 27, 100, this::onClose);
if (status.isBlank()) status("Основа — свойство ванильного предмета. Добавлено и изменено — ваши настройки. Сочетайте любые поддерживаемые свойства.", false);
}
private void scheduleOpen(String id) {
// ChoiceScreen restores this screen after its callback, so open the value editor on the next tick.
selected = id;
private java.util.List<String> filtered() {
String needle = query.toLowerCase(Locale.ROOT);
return properties.present().stream().filter(id -> id.contains(needle) || PropertyModel.label(id).toLowerCase(Locale.ROOT).contains(needle)).toList();
}
private String selected;
@Override public void tick() {
if (selected != null) {
String id = selected;
selected = null;
open(id);
}
public com.google.gson.JsonElement value(String id) { return properties.value(id); }
public com.google.gson.JsonElement example(String id) {
var example = catalog.example(id);
return example.isJsonNull() ? com.google.gson.JsonParser.parseString(online.astradev.plus.editor.form.ComponentExamples.value(id)) : example;
}
public void refresh() { rebuildWidgets(); }
@Override public void tick() { parent.refreshMaterial(); if (pending != null) { String id = pending; pending = null; selected = id; open(id); } }
private void open(String id) {
if (!PropertyForms.open(this, parent, draft, catalog, id)) minecraft.gui.setScreen(new ComponentValueScreen(this, parent, draft, id));
}
private void reset(boolean disabled) {
if (selected == null) { status("Сначала выберите свойство в списке.", false); return; }
draft.removeComponent(selected, disabled);
parent.componentChanged();
rebuildWidgets();
}
@Override public void extractRenderState(GuiGraphicsExtractor graphics, int mouseX, int mouseY, float a) {
super.extractRenderState(graphics, mouseX, mouseY, a);
String material = draft.text("minecraft:paper", "material");
graphics.item(ItemPreview.visual(draft), 18, 37);
graphics.text(font, font.plainSubstrByWidth("Основа: " + ItemPreview.name(draft), width - 226), 42, 35, 0xFFDDEDEA);
graphics.text(font, font.plainSubstrByWidth(material, width - 226), 42, 48, 0xFF9AB5BF);
String count = catalog.hasMaterial(material) ? "Свойств: " + properties.present().size() : "Ожидаем свойства основы…";
graphics.text(font, count, 18, height - 20, 0xFF9AB5BF);
}
private void open(String id) { minecraft.gui.setScreen(new ComponentValueScreen(this, parent, draft, id)); }
@Override public void onClose() { minecraft.gui.setScreen(parent); }
}
@@ -5,7 +5,6 @@ import com.google.gson.JsonParser;
import net.minecraft.client.gui.components.MultiLineEditBox;
import net.minecraft.client.gui.screens.ConfirmScreen;
import net.minecraft.network.chat.Component;
import online.astradev.plus.editor.form.ComponentExamples;
import online.astradev.plus.editor.form.ContentDraft;
public final class ComponentValueScreen extends EditorScreen {
@@ -24,7 +23,7 @@ public final class ComponentValueScreen extends EditorScreen {
this.id = id;
var component = draft.get("components", id);
initial = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create().toJson(
component.isJsonNull() ? JsonParser.parseString(ComponentExamples.value(id)) : component);
component.isJsonNull() ? parent.value(id) : component);
value = initial;
}
@@ -42,7 +41,7 @@ public final class ComponentValueScreen extends EditorScreen {
() -> remove(true));
button("Пример", 20 + part * 2, height - 94, part, () -> {
value = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create()
.toJson(JsonParser.parseString(ComponentExamples.value(id)));
.toJson(parent.example(id));
rebuildWidgets();
});
button("Назад", 12, height - 27, 100, this::onClose);
@@ -0,0 +1,35 @@
package online.astradev.plus.editor.screen;
import java.util.List;
import java.util.function.Consumer;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.screens.Screen;
import online.astradev.plus.editor.client.EditorCatalog;
import online.astradev.plus.editor.form.DataFields;
import online.astradev.plus.editor.form.FormField;
public final class ConditionForms {
private ConditionForms() {}
public static void open(Screen parent, EditorCatalog catalog, JsonObject conditions, Consumer<JsonObject> changed) {
Minecraft.getInstance().gui.setScreen(new SettingsScreen(parent, "Условия взаимодействия", conditions, local -> List.of(
new FormField("sneaking", "Игрок приседает", "Когда разрешено выполнять действие.",
() -> switch (local.text("any", "sneaking")) { case "required" -> "Обязательно"; case "forbidden" -> "Запрещено"; default -> "Не важно"; },
value -> local.string(switch (value) { case "Обязательно" -> "required"; case "Запрещено" -> "forbidden"; default -> "any"; }, "sneaking"),
List.of("Не важно", "Обязательно", "Запрещено"), true),
DataFields.identifiers(local, "Разрешённые блоки", "Пусто: любые блоки. Список также доступен в «Дополнительно».", List.of(), "blocks"),
DataFields.identifiers(local, "Разрешённые измерения", "Пусто: любые измерения. Идентификаторы через запятую.", List.of(), "dimensions")),
changed, List.of(
new SettingsScreen.Action("Выбрать блоки", (screen, local) -> Minecraft.getInstance().gui.setScreen(new IdentifierListScreen(screen,
"Блоки для взаимодействия", array(local.get("blocks")), java.util.stream.Stream.concat(catalog.values("blocks").stream(),
catalog.values("customBlocks").stream()).distinct().sorted().toList(), 256, false, value -> local.set(value, "blocks")))),
new SettingsScreen.Action("Выбрать измерения", (screen, local) -> Minecraft.getInstance().gui.setScreen(new IdentifierListScreen(screen,
"Разрешённые измерения", array(local.get("dimensions")), catalog.values("dimensions"), 64, false, value -> local.set(value, "dimensions"))))),
"ПКМ: проверяется нажатый блок. Установка: блок опоры снизу. Пустые списки не ограничивают действие."));
}
static JsonArray array(com.google.gson.JsonElement value) { return value.isJsonArray() ? value.getAsJsonArray() : new JsonArray(); }
static JsonObject object(com.google.gson.JsonElement value) { return value.isJsonObject() ? value.getAsJsonObject() : new JsonObject(); }
}
@@ -21,7 +21,6 @@ public final class ContentBrowserScreen extends EditorScreen {
private String query = "";
private int searchDelay;
private int requestGeneration;
private boolean first = true;
public ContentBrowserScreen(EditorConnection connection) {
super("AstraPlus: предметы и блоки");
@@ -49,13 +48,10 @@ public final class ContentBrowserScreen extends EditorScreen {
button("←", 12, height - 27, 30, () -> { if (page > 0) { page--; refresh(); } });
button("→", 48, height - 27, 30, () -> { if (page + 1 < pages) { page++; refresh(); } });
button("Закрыть", width - 102, height - 27, 90, this::onClose);
if (first) {
first = false;
connection.request("catalog", new JsonObject(), response -> {
if (EditorConnection.success(response)) catalog.update(response);
else reply(response);
});
}
connection.request("catalog", new JsonObject(), response -> {
if (EditorConnection.success(response)) catalog.update(response);
else reply(response);
});
refresh();
}
@@ -14,6 +14,7 @@ import net.minecraft.client.gui.components.Tooltip;
import net.minecraft.client.gui.screens.ConfirmScreen;
import net.minecraft.network.chat.Component;
import online.astradev.plus.editor.client.EditorCatalog;
import online.astradev.plus.editor.client.ItemPreview;
import online.astradev.plus.editor.form.ContentDraft;
import online.astradev.plus.editor.form.ContentFields;
import online.astradev.plus.editor.form.FormField;
@@ -31,6 +32,8 @@ public final class ContentEditorScreen extends EditorScreen {
private int page;
private boolean saving;
private Button save;
private String requestedMaterial = "";
private int materialDelay;
public ContentEditorScreen(ContentBrowserScreen parent, EditorConnection connection, EditorCatalog catalog, ContentDraft draft) {
super(draft.block() ? "AstraPlus: редактор блока" : "AstraPlus: редактор предмета");
@@ -42,30 +45,32 @@ public final class ContentEditorScreen extends EditorScreen {
@Override protected void init() {
labels.clear();
int tabWidth = (width - 32) / 3;
button("Основное", 12, 38, tabWidth, () -> section(0));
button("Свойства", 16 + tabWidth, 38, tabWidth, () -> section(1));
if (draft.block()) button("Блок", 20 + tabWidth * 2, 38, tabWidth, () -> section(2));
else button("Зачарования", 20 + tabWidth * 2, 38, tabWidth, this::enchantments);
int top = 76;
int tabWidth = (width - 36) / 4;
button("Основное", 12, 76, tabWidth, () -> section(0));
button("Свойства", 16 + tabWidth, 76, tabWidth, () -> minecraft.gui.setScreen(new ComponentListScreen(this, draft, catalog)));
button("Взаимодействия", 20 + tabWidth * 2, 76, tabWidth, () -> minecraft.gui.setScreen(new BehaviorScreen(this, draft, catalog)));
if (draft.block()) button("Блок", 24 + tabWidth * 3, 76, tabWidth, () -> section(2));
else button("Зачарования", 24 + tabWidth * 3, 76, tabWidth, this::enchantments);
int top = 118;
var fieldSource = new ContentFields(draft, catalog);
var fields = switch (section) { case 1 -> fieldSource.properties(); case 2 -> fieldSource.block(); default -> fieldSource.basic(); };
var fields = section == 2 ? fieldSource.block() : fieldSource.basic();
int columns = width >= 560 ? 2 : 1;
int rowCount = Math.max(1, (height - top - 110) / 42);
int rowCount = Math.max(1, (height - top - 103) / 46);
int perPage = columns * rowCount;
int pages = Math.max(1, (fields.size() + perPage - 1) / perPage);
page = Math.min(page, pages - 1);
int fieldWidth = (width - 24 - (columns - 1) * 14) / columns;
for (int index = page * perPage; index < Math.min(fields.size(), (page + 1) * perPage); index++) {
int relative = index - page * perPage;
field(fields.get(index), 12 + (relative % columns) * (fieldWidth + 14), top + (relative / columns) * 42, fieldWidth);
field(fields.get(index), 12 + (relative % columns) * (fieldWidth + 14), top + (relative / columns) * 46, fieldWidth);
}
int bottom = height - 94;
button("←", 12, bottom, 26, () -> { if (page > 0) { page--; rebuildWidgets(); } });
button("→", 42, bottom, 26, () -> { if (page + 1 < pages) { page++; rebuildWidgets(); } });
labels.add(new Label("Поля " + (page + 1) + "/" + pages, 75, bottom + 6));
button("Компоненты", width - 132, bottom, 120, () -> minecraft.gui.setScreen(new ComponentListScreen(this, draft, catalog)));
if (draft.block() && width >= 420) button("Зачарования", width - 262, bottom, 122, this::enchantments);
if (pages > 1) {
button("←", 12, bottom, 26, () -> { if (page > 0) { page--; rebuildWidgets(); } }).active = page > 0;
button("→", 42, bottom, 26, () -> { if (page + 1 < pages) { page++; rebuildWidgets(); } }).active = page + 1 < pages;
labels.add(new Label("Поля " + (page + 1) + "/" + pages, 75, bottom + 6));
}
if (draft.block()) button("Зачарования", width - 142, bottom, 130, this::enchantments);
int size = (width - 40) / 3;
button("Назад", 12, height - 27, size, this::onClose);
save = button("Сохранить", 20 + size, height - 27, size, "Проверить и применить определение на сервере.", this::save);
@@ -93,6 +98,8 @@ public final class ContentEditorScreen extends EditorScreen {
var input = addRenderableWidget(new EditBox(font, x, y, width - (picker ? 30 : 0), 20, Component.literal(field.label())));
input.setMaxLength(Math.max(value.length(), field.key().equals("name") ? 256 : 1024));
input.setValue(value);
if (value.isEmpty()) input.setHint(Component.literal(field.key().equals("drop") ? "По умолчанию: 1"
: section == 2 ? "Наследуется от основы" : field.hint()));
input.setTooltip(Tooltip.create(Component.literal(field.hint())));
input.setResponder(text -> edit(field, text));
if (picker) button("…", x + width - 26, y, 26, () -> minecraft.gui.setScreen(new ChoiceScreen(this,
@@ -103,6 +110,7 @@ public final class ContentEditorScreen extends EditorScreen {
typed.put(field.key(), value);
try {
field.write().accept(value);
if (field.key().equals("material")) materialDelay = 10;
typed.remove(field.key());
errors.remove(field.key());
status("Черновик изменён. Сохраните, чтобы применить.", false);
@@ -120,6 +128,25 @@ public final class ContentEditorScreen extends EditorScreen {
private void enchantments() { minecraft.gui.setScreen(new EnchantmentScreen(this, draft, catalog)); }
@Override public void tick() {
refreshMaterial();
}
public void refreshMaterial() {
if (materialDelay > 0) { materialDelay--; return; }
String material = draft.text("minecraft:paper", "material");
if (catalog.hasMaterial(material) || material.equals(requestedMaterial) || !connection.available()) return;
if (!material.matches("[a-z0-9_.-]+:[a-z0-9_./-]+")) return;
requestedMaterial = material;
var request = new JsonObject(); request.addProperty("id", material);
connection.request("material", request, response -> {
if (EditorConnection.success(response)) {
catalog.material(response);
if (minecraft.gui.screen() instanceof ComponentListScreen screen) screen.refresh();
} else status("Не удалось получить свойства основы: " + EditorConnection.message(response), true);
});
}
private void save() {
if (saving) return;
if (!errors.isEmpty()) { status(errors.values().iterator().next(), true); return; }
@@ -149,6 +176,11 @@ public final class ContentEditorScreen extends EditorScreen {
@Override public void extractRenderState(GuiGraphicsExtractor graphics, int mouseX, int mouseY, float a) {
super.extractRenderState(graphics, mouseX, mouseY, a);
graphics.fill(12, 36, width - 12, 69, 0xFF1B2830);
graphics.item(ItemPreview.visual(draft), 18, 44);
graphics.text(font, font.plainSubstrByWidth(draft.text(draft.id(), "name") + (draft.dirty() ? " Черновик" : " Сохранено"), width - 62), 42, 41, 0xFFE4F2EF);
String base = "Основа: " + ItemPreview.name(draft) + " " + draft.text("minecraft:paper", "material");
graphics.text(font, font.plainSubstrByWidth(base, width - 62), 42, 55, 0xFF94B3BD);
for (var label : labels) graphics.text(font, label.value, label.x, label.y, 0xFFB3C8D1);
}
@@ -0,0 +1,102 @@
package online.astradev.plus.editor.screen;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import net.minecraft.client.gui.screens.Screen;
import online.astradev.plus.editor.client.EditorCatalog;
import online.astradev.plus.editor.form.DataFields;
import online.astradev.plus.editor.form.EffectNames;
import online.astradev.plus.editor.form.FormField;
/** Lists consumption actions or their individual potion effects, preserving unknown effect fields. */
public final class EffectListScreen extends EditorScreen {
private final Screen parent;
private final EditorCatalog catalog;
private final Consumer<JsonArray> changed;
private final JsonArray entries;
private final boolean actions;
private int selected = -1;
public EffectListScreen(Screen parent, EditorCatalog catalog, JsonArray entries, boolean actions, Consumer<JsonArray> changed) {
this(parent, catalog, entries, actions, changed, actions ? "Действия после использования" : "Эффекты состояния");
}
public EffectListScreen(Screen parent, EditorCatalog catalog, JsonArray entries, boolean actions, Consumer<JsonArray> changed, String title) {
super(title);
this.parent = parent;
this.catalog = catalog;
this.entries = entries.deepCopy();
this.actions = actions;
this.changed = changed;
}
@Override protected void init() {
var rows = new ArrayList<String>();
for (int index = 0; index < entries.size(); index++) {
if (!entries.get(index).isJsonObject()) { rows.add((index + 1) + ". Неверный формат строки"); continue; }
var value = entries.get(index).getAsJsonObject();
rows.add((index + 1) + ". " + (actions ? EffectNames.action(value) : EffectNames.effect(value)));
}
var list = addRenderableWidget(new ChoiceList(minecraft, 18, 42, width - 36, Math.max(30, height - 135), value -> {
selected = Integer.parseInt(value.substring(0, value.indexOf('.'))) - 1;
edit();
}));
list.values(rows);
button("Добавить", 18, height - 89, 120, () -> {
if (entries.size() >= 64) { status("Не больше 64 действий или эффектов в этом списке.", true); return; }
var value = JsonParser.parseString(actions
? "{\"type\":\"minecraft:apply_effects\",\"probability\":1,\"effects\":[{\"id\":\"minecraft:regeneration\",\"duration\":100,\"amplifier\":0}]}"
: "{\"id\":\"minecraft:regeneration\",\"duration\":100,\"amplifier\":0}").getAsJsonObject();
entries.add(value);
selected = entries.size() - 1;
changed.accept(entries.deepCopy());
edit();
});
button("Удалить выбранное", 148, height - 89, Math.min(174, width - 166), () -> {
if (selected >= 0 && selected < entries.size()) { entries.remove(selected); selected = -1; changed.accept(entries.deepCopy()); rebuildWidgets(); }
}).active = selected >= 0 && selected < entries.size();
button("Готово", 18, height - 27, 120, this::onClose);
status(entries.isEmpty() ? "Список пуст. Добавьте нужные эффекты." : "Нажмите строку, чтобы изменить её. Эффекты независимы от ванильной основы предмета.", false);
}
private void edit() {
int index = selected;
if (!entries.get(index).isJsonObject()) { status("Для строки нужен объект. Удалите её или исправьте компонент в расширенном JSON.", true); return; }
var value = entries.get(index).getAsJsonObject();
if (actions) {
var extras = List.of(new SettingsScreen.Action("Эффекты…", (screen, local) -> {
var effects = local.get("effects");
minecraft.gui.setScreen(new EffectListScreen(screen, catalog, effects.isJsonArray() ? effects.getAsJsonArray() : new JsonArray(), false,
array -> local.set(array, "effects")));
}));
minecraft.gui.setScreen(new SettingsScreen(this, "Действие с эффектами", value,
local -> List.of(new FormField("type", "Тип действия", "Наложить эффекты или очистить все текущие эффекты.",
() -> local.text("minecraft:apply_effects", "type").equals("minecraft:clear_all_effects") ? "Снять все эффекты" : "Наложить эффекты",
text -> local.string(text.equals("Снять все эффекты") ? "minecraft:clear_all_effects" : "minecraft:apply_effects", "type"),
List.of("Наложить эффекты", "Снять все эффекты"), true),
DataFields.number(local, "Вероятность", "От 0 до 1; используется для наложения эффектов.", "1", false, 0, 1, "probability")),
edited -> replace(index, edited), extras, "Настройте тип действия и отдельные эффекты. Изменения применяются в черновик."));
} else {
minecraft.gui.setScreen(new SettingsScreen(this, "Эффект состояния", value, local -> List.of(
new FormField("id", "Эффект", "Выберите эффект Minecraft.", () -> EffectNames.label(local.text("minecraft:regeneration", "id")),
text -> local.string(catalog.values("effects").stream().filter(id -> EffectNames.label(id).equals(text)).findFirst().orElse(text), "id"),
catalog.values("effects").stream().map(EffectNames::label).sorted().toList(), false),
DataFields.number(local, "Длительность, тики", "20 тиков = 1 секунда; -1 — бесконечный эффект.", "100", true, -1, Integer.MAX_VALUE, "duration"),
DataFields.number(local, "Усилитель", "0 — уровень I, 1 — уровень II.", "0", true, 0, 255, "amplifier"),
DataFields.bool(local, "Показывать частицы", true, "show_particles"),
DataFields.bool(local, "Показывать значок", true, "show_icon")), edited -> replace(index, edited), List.of(),
"Используются обычные эффекты Minecraft. Точный формат проверит сервер."));
}
}
private void replace(int index, JsonObject edited) {
entries.set(index, edited);
changed.accept(entries.deepCopy());
}
@Override public void onClose() { minecraft.gui.setScreen(parent); }
}
@@ -0,0 +1,56 @@
package online.astradev.plus.editor.screen;
import java.util.List;
import java.util.function.Consumer;
import com.google.gson.JsonArray;
import net.minecraft.client.gui.screens.Screen;
/** Visual list editor; repeated entries can represent repeated crafting ingredients. */
public final class IdentifierListScreen extends EditorScreen {
private final Screen parent;
private final List<String> choices;
private final JsonArray values;
private final Consumer<JsonArray> changed;
private final int maximum;
private final boolean duplicates;
private int selected = -1;
private String pending;
public IdentifierListScreen(Screen parent, String title, JsonArray values, List<String> choices,
int maximum, boolean duplicates, Consumer<JsonArray> changed) {
super(title);
this.parent = parent;
this.values = values.deepCopy();
this.choices = choices;
this.maximum = maximum;
this.duplicates = duplicates;
this.changed = changed;
}
@Override protected void init() {
var list = addRenderableWidget(new ChoiceList(minecraft, 12, 40, width - 24, Math.max(26, height - 137),
row -> { selected = Integer.parseInt(row.substring(0, row.indexOf('.'))) - 1; rebuildWidgets(); }));
var labels = new java.util.ArrayList<String>();
for (int i = 0; i < values.size(); i++) labels.add((i + 1) + ". " + values.get(i).getAsString());
list.values(labels);
button("+ Добавить", 12, height - 88, 120, () -> minecraft.gui.setScreen(new ChoiceScreen(this,
"Выберите идентификатор", choices, id -> pending = id))).active = values.size() < maximum;
button("Убрать выбранное", 140, height - 88, Math.min(168, width - 152), () -> {
if (selected < 0 || selected >= values.size()) return;
values.remove(selected); selected = -1; changed.accept(values.deepCopy()); rebuildWidgets();
}).active = selected >= 0;
button("Готово", 12, height - 27, 120, this::onClose);
status(values.isEmpty() ? "Список пуст. Нажмите «Добавить», чтобы выбрать элемент."
: "Элементов: " + values.size() + " / " + maximum + (duplicates ? ". Повторы сохраняются." : "."), false);
}
@Override public void tick() {
if (pending == null) return;
String id = pending; pending = null;
boolean present = java.util.stream.StreamSupport.stream(values.spliterator(), false).anyMatch(value -> value.getAsString().equals(id));
if (values.size() < maximum && (duplicates || !present)) { values.add(id); changed.accept(values.deepCopy()); }
rebuildWidgets();
}
@Override public void onClose() { minecraft.gui.setScreen(parent); }
}
@@ -0,0 +1,45 @@
package online.astradev.plus.editor.screen;
import java.util.function.Consumer;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import net.minecraft.client.gui.components.MultiLineEditBox;
import net.minecraft.client.gui.screens.ConfirmScreen;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.network.chat.Component;
public final class JsonObjectScreen extends EditorScreen {
private final Screen parent;
private final Consumer<JsonObject> changed;
private final String initial;
private String value;
public JsonObjectScreen(Screen parent, String title, JsonObject initial, Consumer<JsonObject> changed) {
super(title); this.parent = parent; this.changed = changed;
this.initial = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create().toJson(initial);
this.value = this.initial;
}
@Override protected void init() {
var input = addRenderableWidget(MultiLineEditBox.builder().setX(12).setY(40).setShowDecorations(false)
.setPlaceholder(Component.literal("{}")).build(font, width - 24, Math.max(30, height - 113), Component.literal("Параметры JSON")));
input.setCharacterLimit(Math.max(8192, value.length()));
input.setValue(value); input.setValueListener(text -> value = text);
button("Назад", 12, height - 27, 110, this::onClose);
button("В форму", width - 132, height - 27, 120, () -> {
try {
var parsed = JsonParser.parseString(value);
if (!parsed.isJsonObject()) throw new IllegalArgumentException("Нужен объект JSON.");
changed.accept(parsed.getAsJsonObject()); minecraft.gui.setScreen(parent);
} catch (RuntimeException error) { status("Ошибка JSON: " + error.getMessage(), true); }
});
if (status.isBlank()) status("Дополнительные параметры сценария. Их названия и смысл определяет автор скрипта.", false);
}
@Override public void onClose() {
if (!initial.equals(value)) minecraft.gui.setScreen(new ConfirmScreen(discard -> minecraft.gui.setScreen(discard ? parent : this),
Component.literal("Отменить изменения параметров?"), Component.literal("JSON ещё не перенесён в форму.")));
else minecraft.gui.setScreen(parent);
}
}
@@ -0,0 +1,62 @@
package online.astradev.plus.editor.screen;
import java.util.List;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import net.minecraft.client.Minecraft;
import online.astradev.plus.editor.client.EditorCatalog;
import online.astradev.plus.editor.form.ContentDraft;
import online.astradev.plus.editor.form.DataFields;
import online.astradev.plus.editor.form.FormField;
import online.astradev.plus.editor.form.PropertyModel;
/** Common codecs get typed forms; every other supported component remains accessible. */
public final class PropertyForms {
private PropertyForms() {}
public static boolean open(ComponentListScreen parent, ContentEditorScreen editor, ContentDraft draft, EditorCatalog catalog, String id) {
JsonElement value = new PropertyModel(draft, catalog).value(id);
boolean primitive = List.of("minecraft:max_damage", "minecraft:max_stack_size", "minecraft:damage", "minecraft:repair_cost", "minecraft:enchantment_glint_override").contains(id);
if (!primitive && !List.of("minecraft:food", "minecraft:consumable", "minecraft:death_protection", "minecraft:damage_resistant", "minecraft:enchantable", "minecraft:unbreakable").contains(id)) return false;
var initial = new JsonObject();
if (primitive) initial.add("value", value); else if (value.isJsonObject()) initial = value.getAsJsonObject();
List<SettingsScreen.Action> actions = id.equals("minecraft:consumable") || id.equals("minecraft:death_protection")
? List.of(new SettingsScreen.Action("Эффекты…", (screen, local) -> {
String path = id.equals("minecraft:consumable") ? "on_consume_effects" : "death_effects";
var effects = local.get(path);
Minecraft.getInstance().gui.setScreen(new EffectListScreen(screen, catalog, effects.isJsonArray() ? effects.getAsJsonArray() : new JsonArray(), true,
array -> local.set(array, path), id.equals("minecraft:death_protection") ? "Защита от смерти: действия" : "При употреблении: действия"));
})) : List.of();
Minecraft.getInstance().gui.setScreen(new SettingsScreen(parent, PropertyModel.label(id), initial, local -> fields(local, id), edited -> {
draft.component(primitive ? edited.get("value") : edited, id);
editor.componentChanged();
}, actions, switch (id) {
case "minecraft:food" -> "Питание определяет сытость. Для употребления добавьте также свойство «Употребление и эффекты».";
case "minecraft:death_protection" -> "Свойство спасает от смертельного урона, как тотем, и расходует один предмет. Настройте эффекты после спасения.";
case "minecraft:unbreakable" -> "Присутствие этого свойства отключает расход прочности. Для выключения используйте «Отключить» в списке свойств.";
default -> "Это отдельное свойство выбранного предмета. Остальные компоненты и неизвестные поля сохраняются.";
}));
return true;
}
private static List<FormField> fields(ContentDraft local, String id) {
return switch (id) {
case "minecraft:max_damage" -> List.of(DataFields.number(local, "Запас прочности", "Положительное целое число. Повреждаемые предметы не складываются в стопки.", "1800", true, 1, Integer.MAX_VALUE, "value"));
case "minecraft:max_stack_size" -> List.of(DataFields.number(local, "Максимум в стопке", "Minecraft допускает 1–99. Несовместимость с прочностью проверит сервер.", "64", true, 1, 99, "value"));
case "minecraft:damage", "minecraft:repair_cost" -> List.of(DataFields.number(local, "Значение", "Неотрицательное целое число.", "0", true, 0, Integer.MAX_VALUE, "value"));
case "minecraft:enchantment_glint_override" -> List.of(DataFields.bool(local, "Показывать блеск", true, "value"));
case "minecraft:food" -> List.of(DataFields.number(local, "Питание", "Сколько единиц голода восстанавливает предмет.", "6", true, 0, Integer.MAX_VALUE, "nutrition"),
DataFields.number(local, "Насыщение", "Дополнительный запас насыщения; прямое значение.", "7.2", false, -Float.MAX_VALUE, Float.MAX_VALUE, "saturation"),
DataFields.bool(local, "Можно есть при полном голоде", false, "can_always_eat"));
case "minecraft:consumable" -> List.of(DataFields.number(local, "Время употребления, секунды", "0 — мгновенное применение.", "1.6", false, 0, Float.MAX_VALUE, "consume_seconds"),
DataFields.choice(local, "Анимация", "Обычная клиентская анимация Minecraft.", "eat", List.of("eat", "drink", "none", "block", "bow", "spear", "crossbow", "spyglass", "toot_horn", "brush"), "animation"),
DataFields.text(local, "Звук", "Идентификатор звука Minecraft.", "minecraft:entity.generic.eat", List.of(), "sound"),
DataFields.bool(local, "Частицы предмета", true, "has_consume_particles"));
case "minecraft:damage_resistant" -> List.of(DataFields.text(local, "Типы урона", "#minecraft:is_fire защищает лежащий предмет от огня и лавы.", "#minecraft:is_fire", List.of("#minecraft:is_fire", "#minecraft:is_explosion"), "types"));
case "minecraft:enchantable" -> List.of(DataFields.number(local, "Зачаровываемость", "Положительное значение для стола зачарований.", "15", true, 1, Integer.MAX_VALUE, "value"));
default -> List.of();
};
}
}
@@ -0,0 +1,48 @@
package online.astradev.plus.editor.screen;
import java.util.List;
import java.util.function.Consumer;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiGraphicsExtractor;
import net.minecraft.client.gui.components.ObjectSelectionList;
import net.minecraft.client.input.MouseButtonEvent;
import net.minecraft.network.chat.Component;
import online.astradev.plus.editor.form.PropertyModel;
/** Two-line property rows keep provenance visible while leaving values readable. */
public final class PropertyList extends ObjectSelectionList<PropertyList.Row> {
private final PropertyModel properties;
private final Consumer<String> selected;
public PropertyList(Minecraft minecraft, int x, int y, int width, int height, PropertyModel properties, Consumer<String> selected) {
super(minecraft, width, height, y, 40);
setX(x);
this.properties = properties;
this.selected = selected;
}
public void values(List<String> ids) { clearEntries(); ids.forEach(id -> addEntry(new Row(id))); }
public void select(String id) { children().stream().filter(row -> row.id.equals(id)).findFirst().ifPresent(this::setSelected); }
@Override public int getRowWidth() { return width - 16; }
public final class Row extends ObjectSelectionList.Entry<Row> {
private final String id;
private Row(String id) { this.id = id; }
@Override public Component getNarration() { return Component.literal(PropertyModel.label(id) + ", " + properties.state(id)); }
@Override public void extractContent(GuiGraphicsExtractor graphics, int mouseX, int mouseY, boolean hovered, float a) {
int x = getContentX() + 5, y = getContentY() + 5, rowWidth = getContentWidth() - 10;
graphics.fill(getX(), getY(), getX() + getWidth(), getY() + getHeight() - 2, getSelected() == this ? 0xFF304C53 : hovered ? 0xFF293D46 : 0xFF1B2830);
String state = properties.state(id);
int color = state.equals("Основа") ? 0xFF91A6B2 : state.equals("Отключено") ? 0xFFF0AE96 : 0xFF93DEC2;
graphics.text(minecraft.font, minecraft.font.plainSubstrByWidth(PropertyModel.label(id), rowWidth - 88), x, y, 0xFFE5EFF1);
graphics.text(minecraft.font, state, x + rowWidth - minecraft.font.width(state), y, color);
String detail = state.equals("Отключено") ? "Свойство удалено у этого предмета" : properties.summary(id);
graphics.text(minecraft.font, minecraft.font.plainSubstrByWidth(detail, rowWidth), x, y + 14, 0xFF9AAFB8);
}
@Override public boolean mouseClicked(MouseButtonEvent event, boolean doubleClick) {
if (event.button() != 0) return false;
setSelected(this);
selected.accept(id);
return true;
}
}
}
@@ -0,0 +1,67 @@
package online.astradev.plus.editor.screen;
import java.util.List;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import net.minecraft.client.gui.screens.Screen;
import online.astradev.plus.editor.client.EditorCatalog;
import online.astradev.plus.editor.form.ContentDraft;
import online.astradev.plus.editor.form.DataFields;
import online.astradev.plus.editor.form.FormField;
public final class ScriptBindingsScreen extends EditorScreen {
private static final List<String> EVENTS = List.of("ПКМ по блоку", "ПКМ в воздух", "Установка блока", "Разрушение блока");
private static final List<String> EVENT_IDS = List.of("use_on_block", "use_in_air", "place_block", "break_block");
private final Screen parent;
private final ContentDraft draft;
private final EditorCatalog catalog;
private final Runnable changed;
private int selected = -1;
public ScriptBindingsScreen(Screen parent, ContentDraft draft, EditorCatalog catalog, Runnable changed) {
super("Сценарии JavaScript");
this.parent = parent; this.draft = draft; this.catalog = catalog; this.changed = changed;
}
private JsonArray bindings() { return ConditionForms.array(draft.get("interactions")); }
@Override protected void init() {
var values = bindings();
var list = addRenderableWidget(new ChoiceList(minecraft, 12, 42, width - 24, Math.max(26, height - 143), label -> {
selected = Integer.parseInt(label.substring(0, label.indexOf('.'))) - 1; rebuildWidgets();
}));
var labels = new java.util.ArrayList<String>();
for (int index = 0; index < values.size(); index++) {
var binding = new ContentDraft(values.get(index).getAsJsonObject(), "form");
int event = EVENT_IDS.indexOf(binding.text("", "event"));
labels.add((index + 1) + ". " + (event < 0 ? binding.text("", "event") : EVENTS.get(event)) + " → " + binding.text("", "script"));
}
list.values(labels);
int third = (width - 32) / 3;
button("+ Добавить", 12, height - 90, third, () -> edit(-1)).active = values.size() < 16;
button("Изменить", 16 + third, height - 90, third, () -> edit(selected)).active = selected >= 0 && selected < values.size();
button("Убрать", 20 + third * 2, height - 90, third, () -> {
var entries = bindings(); entries.remove(selected); draft.set(entries, "interactions"); selected = -1; changed.run(); rebuildWidgets();
}).active = selected >= 0 && selected < values.size();
button("Назад", 12, height - 27, 110, this::onClose);
status("Событие запускает серверный .js. Каждая привязка имеет собственные условия и параметры. Привязок: " + values.size() + "/16.", false);
}
private void edit(int index) {
var value = index < 0 ? new JsonObject() : bindings().get(index).getAsJsonObject();
if (index < 0) { value.addProperty("event", "use_on_block"); value.addProperty("script", catalog.values("scripts").stream().findFirst().orElse("")); }
minecraft.gui.setScreen(new SettingsScreen(this, "Привязка сценария", value, local -> List.of(
new FormField("event", "Событие", "Когда сервер вызывает сценарий.", () -> {
int event = EVENT_IDS.indexOf(local.text("use_on_block", "event")); return event < 0 ? local.text("", "event") : EVENTS.get(event);
}, event -> local.string(EVENT_IDS.get(EVENTS.indexOf(event)), "event"), EVENTS, true),
DataFields.text(local, "Сценарий", "namespace:путь файла .js из серверного каталога scripts.", "", catalog.values("scripts"), "script")),
result -> { var entries = bindings(); if (index < 0) entries.add(result); else entries.set(index, result); draft.set(entries, "interactions"); changed.run(); },
List.of(new SettingsScreen.Action("Условия", (screen, local) -> ConditionForms.open(screen, catalog,
ConditionForms.object(local.get("conditions")), conditions -> local.set(conditions, "conditions"))),
new SettingsScreen.Action("Параметры JSON", (screen, local) -> minecraft.gui.setScreen(new JsonObjectScreen(screen,
"Параметры сценария", ConditionForms.object(local.get("parameters")), parameters -> local.set(parameters, "parameters"))))),
"Исходный код хранится на сервере. Выберите событие и сценарий; условия и параметры доступны в «Дополнительно»."));
}
@Override public void onClose() { minecraft.gui.setScreen(parent); }
}
@@ -0,0 +1,124 @@
package online.astradev.plus.editor.screen;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import com.google.gson.JsonObject;
import net.minecraft.client.gui.GuiGraphicsExtractor;
import net.minecraft.client.gui.components.EditBox;
import net.minecraft.client.gui.components.Tooltip;
import net.minecraft.client.gui.screens.ConfirmScreen;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.network.chat.Component;
import online.astradev.plus.editor.form.ContentDraft;
import online.astradev.plus.editor.form.FormField;
/** A transactional form: navigation and invalid input never silently change the parent draft. */
public final class SettingsScreen extends EditorScreen {
public record Action(String label, BiConsumer<SettingsScreen, ContentDraft> open) {}
private final Screen parent;
private final ContentDraft local;
private final Function<ContentDraft, List<FormField>> fields;
private final Consumer<JsonObject> apply;
private final List<Action> actions;
private final Map<String, String> typed = new LinkedHashMap<>();
private final Map<String, String> errors = new LinkedHashMap<>();
private final List<Label> labels = new ArrayList<>();
private int page;
public SettingsScreen(Screen parent, String title, JsonObject initial, Function<ContentDraft, List<FormField>> fields,
Consumer<JsonObject> apply, List<Action> actions, String description) {
super(title);
this.parent = parent;
this.local = new ContentDraft(initial, "form");
this.fields = fields;
this.apply = apply;
this.actions = actions;
status(description, false);
}
@Override protected void init() {
labels.clear();
var fields = this.fields.apply(local);
if (fields.isEmpty()) {
labels.add(new Label("Свойство включится после добавления в черновик.", 18, 53, width - 36));
labels.add(new Label(actions.isEmpty() ? "Дополнительных параметров у него нет." : "Состав эффектов задаётся кнопкой ниже.", 18, 73, width - 36));
}
int columns = width >= 570 ? 2 : 1;
int rows = Math.max(1, (height - 140) / 48);
int count = rows * columns;
int pages = Math.max(1, (fields.size() + count - 1) / count);
page = Math.min(page, pages - 1);
int columnWidth = (width - 36 - 12 * (columns - 1)) / columns;
for (int index = page * count; index < Math.min(fields.size(), (page + 1) * count); index++) {
var field = fields.get(index);
int relative = index - page * count, x = 18 + relative % columns * (columnWidth + 12), y = 58 + relative / columns * 48;
labels.add(new Label(field.label(), x, y - 13, columnWidth));
String value = typed.getOrDefault(field.key(), field.read().get());
if (field.cycle()) {
button(value, x, y, columnWidth, field.hint(), () -> {
int current = field.choices().indexOf(field.read().get());
edit(field, field.choices().get((current + 1) % field.choices().size()));
rebuildWidgets();
});
} else {
boolean picker = !field.choices().isEmpty();
var box = addRenderableWidget(new EditBox(font, x, y, columnWidth - (picker ? 29 : 0), 20, Component.literal(field.label())));
box.setMaxLength(Math.max(value.length(), 8192));
box.setValue(value);
box.setHint(Component.literal(field.hint()));
box.setTooltip(Tooltip.create(Component.literal(field.hint())));
box.setResponder(text -> edit(field, text));
if (picker) button("…", x + columnWidth - 25, y, 25, () -> minecraft.gui.setScreen(
new ChoiceScreen(this, field.label(), field.choices(), choice -> edit(field, choice))));
}
}
if (pages > 1) {
button("←", 18, height - 101, 26, () -> { if (page > 0) { page--; rebuildWidgets(); } }).active = page > 0;
button("→", 48, height - 101, 26, () -> { if (page + 1 < pages) { page++; rebuildWidgets(); } }).active = page + 1 < pages;
labels.add(new Label((page + 1) + " / " + pages, 84, height - 94, 80));
}
if (!actions.isEmpty()) button(actions.size() == 1 ? actions.getFirst().label() : "Дополнительно…", width - 177, height - 101, 159, () -> {
if (!errors.isEmpty()) { status(errors.values().iterator().next(), true); return; }
if (actions.size() == 1) { actions.getFirst().open().accept(this, local); return; }
minecraft.gui.setScreen(new ChoiceScreen(this, "Дополнительные настройки", actions.stream().map(Action::label).toList(), selected -> pending = selected));
});
button("Назад", 18, height - 27, 110, this::onClose);
button("В черновик", width - 148, height - 27, 130, () -> {
if (!errors.isEmpty()) { status(errors.values().iterator().next(), true); return; }
apply.accept(local.document());
minecraft.gui.setScreen(parent);
});
}
private String pending;
@Override public void tick() {
if (pending != null) {
String selected = pending; pending = null;
actions.stream().filter(action -> action.label().equals(selected)).findFirst().orElseThrow().open().accept(this, local);
}
}
private void edit(FormField field, String value) {
typed.put(field.key(), value);
try { field.write().accept(value); typed.remove(field.key()); errors.remove(field.key()); }
catch (IllegalArgumentException error) { errors.put(field.key(), field.label() + ": " + error.getMessage()); status(errors.get(field.key()), true); }
}
@Override public void extractRenderState(GuiGraphicsExtractor graphics, int mouseX, int mouseY, float a) {
super.extractRenderState(graphics, mouseX, mouseY, a);
labels.forEach(label -> graphics.text(font, font.plainSubstrByWidth(label.text(), label.width()), label.x(), label.y(), 0xFFB9CDD3));
}
@Override public void onClose() {
if (local.dirty() || !errors.isEmpty()) minecraft.gui.setScreen(new ConfirmScreen(discard -> minecraft.gui.setScreen(discard ? parent : this),
Component.literal("Вернуться без применения?"), Component.literal("Изменения этой формы ещё не перенесены в черновик.")));
else minecraft.gui.setScreen(parent);
}
private record Label(String text, int x, int y, int width) {}
}