LibJF/libjf-config-ui-tiny/src/client/java/io/gitlab/jfronny/libjf/config/impl/ui/tiny/TinyConfigScreenFactory.java

80 lines
3.5 KiB
Java

package io.gitlab.jfronny.libjf.config.impl.ui.tiny;
import io.gitlab.jfronny.commons.serialize.gson.api.v2.GsonHolders;
import io.gitlab.jfronny.libjf.LibJf;
import io.gitlab.jfronny.libjf.config.api.v2.ConfigInstance;
import io.gitlab.jfronny.libjf.config.api.v2.EntryInfo;
import io.gitlab.jfronny.libjf.config.api.v2.dsl.CategoryBuilder;
import io.gitlab.jfronny.libjf.config.api.v2.type.Type;
import io.gitlab.jfronny.libjf.config.api.v2.ui.ConfigScreenFactory;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.resource.language.I18n;
import net.minecraft.client.toast.SystemToast;
import net.minecraft.text.Text;
// IDEA doesn't like this, but it does work in practice
public class TinyConfigScreenFactory implements ConfigScreenFactory<Screen, TinyConfigScreenFactory.Built> {
@Override
public Built create(ConfigInstance config, Screen parent) {
if (config.getEntries().size() == 1
&& config.getPresets().keySet().stream().allMatch(s -> s.equals(CategoryBuilder.CONFIG_PRESET_DEFAULT))
&& config.getReferencedConfigs().isEmpty()
&& config.getCategories().isEmpty()) {
EntryInfo entry = config.getEntries().get(0);
Type type = entry.getValueType();
if (!type.isInt() && !type.isLong() && !type.isFloat() && !type.isDouble() && !type.isString() && !type.isBool() && !type.isEnum()) {
final String jsonified;
try {
jsonified = GsonHolders.CONFIG.getGson().toJson(entry.getValue());
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
String key = config.getTranslationPrefix() + entry.getName();
return new Built(new EditorScreen(
Text.translatable(key),
I18n.hasTranslation(key + ".tooltip") ? Text.translatable(key + ".tooltip") : null,
parent,
jsonified,
json -> {
try {
entry.setValue(GsonHolders.CONFIG.getGson().fromJson(json, type.asClass()));
config.write();
} catch (Throwable e) {
LibJf.LOGGER.error("Could not write element", e);
SystemToast.add(
MinecraftClient.getInstance().getToastManager(),
SystemToast.Type.PACK_LOAD_FAILURE,
Text.translatable("libjf-config-ui-tiny.entry.json.write.fail.title"),
Text.translatable("libjf-config-ui-tiny.entry.json.write.fail.description")
);
}
}
));
}
}
return new Built(new TinyConfigScreen(config, parent));
}
@Override
public int getPriority() {
return 0;
}
public record Built(ScreenWithSaveHook screen) implements ConfigScreenFactory.Built<Screen> {
@Override
public Screen get() {
return screen;
}
@Override
public void onSave(Runnable action) {
Runnable currentHook = screen.saveHook;
screen.saveHook = () -> {
currentHook.run();
action.run();
};
}
}
}