Skip to content

Listen for GUI close #81

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions src/main/kotlin/gg/flyte/twilight/gui/GUI.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import net.kyori.adventure.text.Component
import org.bukkit.Bukkit
import org.bukkit.entity.Player
import org.bukkit.event.inventory.InventoryClickEvent
import org.bukkit.event.inventory.InventoryCloseEvent
import org.bukkit.event.inventory.InventoryType
import org.bukkit.inventory.ItemStack

Expand All @@ -26,6 +27,7 @@ class GUI(val title: Component, val size: Int, val type: InventoryType, val cont

private val keySlot = mutableMapOf<Char, MutableList<Int>>()
private val slotAction = mutableMapOf<Int, InventoryClickEvent.() -> Unit>()
private val onClose = mutableListOf<InventoryCloseEvent.() -> Unit>()

lateinit var viewer: Player

Expand All @@ -35,6 +37,12 @@ class GUI(val title: Component, val size: Int, val type: InventoryType, val cont
slotAction[slot]?.invoke(this)
}

private val closeEvent = event<InventoryCloseEvent> {
if (inventory != [email protected]) return@event
onClose.forEach { it.invoke(this) }
remove()
}

fun pattern(vararg pattern: String) {
for ((index, value) in pattern.joinToString("").withIndex()) {
keySlot.getOrPut(value) { mutableListOf() }.add(index)
Expand All @@ -48,6 +56,13 @@ class GUI(val title: Component, val size: Int, val type: InventoryType, val cont
slotAction[-1] = action
}

/**
* Set the action to be executed when the inventory is closed
*/
fun onClose(action: InventoryCloseEvent.() -> Unit) {
onClose.add(action)
}

@JvmName("setSlot")
fun set(slot: Int, item: ItemStack, action: InventoryClickEvent.() -> Unit = {}) {
inventory.setItem(slot, item)
Expand All @@ -74,6 +89,7 @@ class GUI(val title: Component, val size: Int, val type: InventoryType, val cont
slotAction.clear()
inventory.clear()
clickEvent.unregister()
closeEvent.unregister()
}

companion object {
Expand Down