-
-
Save Lemmmy/508d218129b92123f9811dc948931d85 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package io.sc3.main.broadcasts | |
import com.google.gson.JsonDeserializationContext | |
import com.google.gson.JsonDeserializer | |
import com.google.gson.JsonElement | |
import net.minecraft.text.Text | |
import net.minecraft.util.Formatting | |
import net.minecraft.util.Formatting.GREEN | |
import net.minecraft.util.Formatting.WHITE | |
import io.sc3.text.* | |
import io.sc3.utils.text.FontIcons.FONT_WHITE_BULLET | |
import java.lang.reflect.Type | |
data class BroadcastText(val text: Text) { | |
object Deserializer : JsonDeserializer<BroadcastText> { | |
override fun deserialize(json: JsonElement, typeOf: Type, ctx: JsonDeserializationContext): BroadcastText { | |
// Get the outer array of texts to build with | |
if (!json.isJsonArray) { | |
throw IllegalArgumentException("Broadcast text must be an array of strings or objects") | |
} | |
val objects = json.asJsonArray | |
val textBuilder = of("", GREEN) + of("$FONT_WHITE_BULLET ", WHITE) | |
objects.forEach { | |
if (it.isJsonPrimitive) { | |
// If the text is a string, just render it directly as green text | |
textBuilder + of(it.asString) | |
} else { | |
try { | |
// Try our text shorthands | |
val shorthand = ctx.deserialize<Shorthand>(it, Shorthand::class.java) | |
textBuilder + shorthand.toText() | |
} catch (e: Exception) { | |
// Otherwise try vanilla text | |
val vanillaText = ctx.deserialize<Text>(it, Text::class.java) | |
textBuilder + vanillaText | |
} | |
} | |
} | |
return BroadcastText(textBuilder) | |
} | |
} | |
data class Shorthand( | |
val text: String?, | |
val color: String?, | |
val formatting: List<String>?, | |
val url: String?, | |
val command: String?, | |
val copyable: String? | |
) { | |
fun toText(): Text { | |
val formattingCodes = formatting?.toMutableList() ?: mutableListOf() | |
color?.let { formattingCodes.add(0, it) } | |
val formatting = formattingCodes | |
.mapNotNull { Formatting.byName(it) } | |
.toTypedArray() | |
val linkFormatting = formatting.ifEmpty { linkFormatting } | |
return if (url != null) { | |
openableLink(text ?: url, *linkFormatting, link = url) | |
} else if (command != null) { | |
suggestedCommand(text ?: command, *linkFormatting, cmd = command) | |
} else if (copyable != null) { | |
copyable(text ?: copyable, *linkFormatting, clipboardText = copyable) | |
} else { | |
of(text ?: "", *formatting) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment