Skip to content

Commit

Permalink
Add enum arg type
Browse files Browse the repository at this point in the history
  • Loading branch information
andyksaw committed Dec 5, 2024
1 parent c720754 commit caa03ab
Show file tree
Hide file tree
Showing 10 changed files with 131 additions and 44 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import java.util.regex.Pattern
* Converts a non-dash formatted UUID string into a
* dash-formatted UUID string
*/
// TODO: make this an extension of something more specific
fun String.toDashFormattedUUID(): String {
val pattern = Pattern.compile("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})")
return pattern.matcher(this).replaceAll("$1-$2-$3-$4-$5")
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package com.projectcitybuild.pcbridge.paper.core.support.brigadier.arguments

import com.mojang.brigadier.arguments.ArgumentType
import com.mojang.brigadier.arguments.StringArgumentType
import com.mojang.brigadier.context.CommandContext
import com.mojang.brigadier.exceptions.CommandSyntaxException
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType
import com.mojang.brigadier.suggestion.Suggestions
import com.mojang.brigadier.suggestion.SuggestionsBuilder
import io.papermc.paper.command.brigadier.MessageComponentSerializer
import io.papermc.paper.command.brigadier.argument.CustomArgumentType
import net.kyori.adventure.text.Component
import net.kyori.adventure.text.format.NamedTextColor
import java.util.concurrent.CompletableFuture

class EnumArgument<T : Enum<T>>(
private val enumClass: Class<T>,
) : CustomArgumentType.Converted<T, String> {
override fun convert(nativeType: String): T {
return try {
enumClass.enumConstants?.firstOrNull { it.name.equals(nativeType, ignoreCase = true) }
?: throw IllegalArgumentException("Invalid value: $nativeType")
} catch (e: IllegalArgumentException) {
val message = MessageComponentSerializer.message()
.serialize(Component.text("Invalid value: $nativeType", NamedTextColor.RED))

throw CommandSyntaxException(SimpleCommandExceptionType(message), message)
}
}

override fun getNativeType(): ArgumentType<String> {
return StringArgumentType.word()
}

override fun <S : Any> listSuggestions(
context: CommandContext<S>,
builder: SuggestionsBuilder,
): CompletableFuture<Suggestions> {
enumClass.enumConstants?.forEach { value ->
builder.suggest(value.name)
}
return builder.buildFuture()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import net.kyori.adventure.text.Component
import net.kyori.adventure.text.format.NamedTextColor
import java.util.concurrent.CompletableFuture

@Suppress("UnstableApiUsage")
class OnOffArgument: CustomArgumentType.Converted<Boolean, String> {
override fun getNativeType(): ArgumentType<String>
= StringArgumentType.word()
Expand All @@ -33,7 +32,7 @@ class OnOffArgument: CustomArgumentType.Converted<Boolean, String> {

override fun <S : Any> listSuggestions(
context: CommandContext<S>,
builder: SuggestionsBuilder
builder: SuggestionsBuilder,
): CompletableFuture<Suggestions> = builder
.apply {
suggest("on")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,17 @@ package com.projectcitybuild.pcbridge.paper.core.support.brigadier.extensions

import com.mojang.brigadier.context.CommandContext

fun <S, V> CommandContext<S>.getOptionalArgument(name: String, clazz: Class<V>): V? {
fun <S, T> CommandContext<S>.getArgument(
name: String,
clazz: Class<T>,
): T {
return getArgument(name, clazz)
}

fun <S, T> CommandContext<S>.getOptionalArgument(
name: String,
clazz: Class<T>,
): T? {
return try {
getArgument(name, clazz)
} catch (e: IllegalStateException) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package com.projectcitybuild.pcbridge.paper.core.support.component

import net.kyori.adventure.text.Component
import net.kyori.adventure.text.TextComponent

/**
* Joins a collection of components together with the given [separator]
* inserted in between each collection element
*/
fun List<TextComponent.Builder>.join(separator: Component): TextComponent.Builder {
val component = Component.text()
withIndex().forEach { entry ->
component.append(entry.value)

val isLast = entry.index == size - 1
if (!isLast) {
component.append(separator)
}
}
return component
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.projectcitybuild.pcbridge.paper.core.extensions
package com.projectcitybuild.pcbridge.paper.core.support.kotlin

import java.lang.Enum.valueOf

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,15 @@ import com.projectcitybuild.pcbridge.paper.core.support.brigadier.extensions.exe
import com.projectcitybuild.pcbridge.paper.core.support.brigadier.extensions.requiresPermission
import com.projectcitybuild.pcbridge.paper.core.support.brigadier.extensions.suggestsSuspending
import com.projectcitybuild.pcbridge.paper.core.support.brigadier.traceSuspending
import com.projectcitybuild.pcbridge.paper.core.support.component.join
import com.projectcitybuild.pcbridge.paper.features.builds.data.EditableBuildField
import io.papermc.paper.command.brigadier.CommandSourceStack
import io.papermc.paper.command.brigadier.Commands
import net.kyori.adventure.text.minimessage.MiniMessage
import net.kyori.adventure.text.Component
import net.kyori.adventure.text.event.ClickEvent
import net.kyori.adventure.text.event.HoverEvent
import net.kyori.adventure.text.format.NamedTextColor
import net.kyori.adventure.text.format.TextDecoration
import org.bukkit.entity.Player
import org.bukkit.plugin.Plugin

Expand Down Expand Up @@ -51,13 +57,34 @@ class BuildEditCommand(
val build = buildRepository.get(name)
checkNotNull(build) { "Build not found" }

val actions = listOf("name", "description", "lore")
val actionsRow = actions.joinToString(separator = " ") { field ->
val command = "/builds set ${build.id} $field "
"[<white><underlined><click:suggest_command:'$command'><hover:show_text:'$command'>${field.uppercase()}</hover></click></underlined></white>]"
val actions = EditableBuildField.entries
val actionComponents = actions.map { field ->
val existing = when (field) {
EditableBuildField.NAME -> build.name
EditableBuildField.DESCRIPTION -> build.description
EditableBuildField.LORE -> build.lore
}
val command = "/builds set ${build.id} ${field.name} ${existing.orEmpty()}"
val hoverText = "/builds set ${build.id} $field"

Component.text()
.append(Component.text("["))
.append(
Component.text(field.name, NamedTextColor.WHITE)
.decorate(TextDecoration.UNDERLINED)
.clickEvent(ClickEvent.suggestCommand(command))
.hoverEvent(HoverEvent.showText(Component.text(hoverText)))
)
.append(Component.text("]"))
}
val actionComponent = actionComponents.join(
separator = Component.space()
)

context.source.sender.sendMessage(
MiniMessage.miniMessage().deserialize("<gray>Click a field to edit:<newline>$actionsRow</gray>")
Component.text("Click a field to edit:", NamedTextColor.GRAY)
.appendNewline()
.append(actionComponent)
)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,12 @@ import com.mojang.brigadier.tree.LiteralCommandNode
import com.projectcitybuild.pcbridge.paper.PermissionNode
import com.projectcitybuild.pcbridge.paper.features.builds.repositories.BuildRepository
import com.projectcitybuild.pcbridge.paper.core.support.brigadier.BrigadierCommand
import com.projectcitybuild.pcbridge.paper.core.support.brigadier.arguments.EnumArgument
import com.projectcitybuild.pcbridge.paper.core.support.brigadier.extensions.executesSuspending
import com.projectcitybuild.pcbridge.paper.core.support.brigadier.extensions.getOptionalArgument
import com.projectcitybuild.pcbridge.paper.core.support.brigadier.extensions.requiresPermission
import com.projectcitybuild.pcbridge.paper.core.support.brigadier.extensions.suggestsSuspending
import com.projectcitybuild.pcbridge.paper.core.support.brigadier.extensions.getOptionalArgument
import com.projectcitybuild.pcbridge.paper.core.support.brigadier.traceSuspending
import com.projectcitybuild.pcbridge.paper.features.builds.data.EditableBuildField
import io.papermc.paper.command.brigadier.CommandSourceStack
import io.papermc.paper.command.brigadier.Commands
import net.kyori.adventure.text.minimessage.MiniMessage
Expand All @@ -29,17 +30,9 @@ class BuildSetCommand(
.then(
Commands.argument("id", IntegerArgumentType.integer())
.then(
Commands.argument("field", StringArgumentType.word())
.suggests { _, suggestions ->
// TODO: clean this up
suggestions.suggest("description")
suggestions.suggest("name")
suggestions.suggest("lore")
suggestions.buildFuture()
}
Commands.argument("field", EnumArgument(EditableBuildField::class.java))
.then(
Commands.argument("value", StringArgumentType.greedyString())
.suggestsSuspending(plugin, ::suggestDescription)
.executesSuspending(plugin, ::execute)
)
.executesSuspending(plugin, ::execute)
Expand All @@ -48,28 +41,18 @@ class BuildSetCommand(
.build()
}

private suspend fun suggestDescription(
context: CommandContext<CommandSourceStack>,
suggestions: SuggestionsBuilder,
) {
val id = suggestions.remaining

// TODO
}

private suspend fun execute(context: CommandContext<CommandSourceStack>) = context.traceSuspending {
val field = context.getArgument("field", String::class.java)
val field = context.getArgument("field", EditableBuildField::class.java)
val id = context.getArgument("id", Int::class.java)
val value = context.getOptionalArgument("value", String::class.java) ?: ""
val player = context.source.executor as? Player

checkNotNull(player) { "Only a player can use this command" }

val editableField = BuildRepository.EditableField.valueOf(field.uppercase())
buildRepository.set(
id = id,
player = player,
field = editableField,
field = field,
value = value,
)

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package com.projectcitybuild.pcbridge.paper.features.builds.data

enum class EditableBuildField {
NAME,
DESCRIPTION,
LORE,
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,13 @@ import com.projectcitybuild.pcbridge.http.models.pcb.Build
import com.projectcitybuild.pcbridge.http.models.pcb.PaginatedResponse
import com.projectcitybuild.pcbridge.http.services.pcb.BuildHttpService
import com.projectcitybuild.pcbridge.paper.core.support.kotlin.Trie
import com.projectcitybuild.pcbridge.paper.features.builds.data.EditableBuildField
import org.bukkit.Location
import org.bukkit.entity.Player

class BuildRepository(
private val buildHttpService: BuildHttpService,
) {
enum class EditableField {
NAME,
DESCRIPTION,
LORE,
}

class IdMap(
initial: Map<String, Int>,
) {
Expand Down Expand Up @@ -169,17 +164,17 @@ class BuildRepository(
suspend fun set(
id: Int,
player: Player,
field: EditableField,
field: EditableBuildField,
value: String,
): Build {
val build = buildHttpService.set(
id = id,
playerUUID = player.uniqueId,
name = if (field == EditableField.NAME) value else null,
description = if (field == EditableField.DESCRIPTION) value else null,
lore = if (field == EditableField.LORE) value else null,
name = if (field == EditableBuildField.NAME) value else null,
description = if (field == EditableBuildField.DESCRIPTION) value else null,
lore = if (field == EditableBuildField.LORE) value else null,
)
if (field == EditableField.NAME) {
if (field == EditableBuildField.NAME) {
cache?.update(id, newName = build.name)
}
return build
Expand Down

0 comments on commit caa03ab

Please sign in to comment.