menu: improve keyboard navigation

This commit is contained in:
Bixilon 2022-01-29 00:07:13 +01:00
parent 4466a69b41
commit 00c2f7b1bf
No known key found for this signature in database
GPG Key ID: 5CAD791931B09AC4
3 changed files with 28 additions and 7 deletions

View File

@ -54,6 +54,8 @@ abstract class Element(val guiRenderer: GUIRenderer) : InputElement {
protected open var _prefSize: Vec2i = Vec2i.EMPTY protected open var _prefSize: Vec2i = Vec2i.EMPTY
open val canFocus: Boolean get() = false
/** /**
* If maxSize was infinity, what size would the element have? (Excluded margin!) * If maxSize was infinity, what size would the element have? (Excluded margin!)
*/ */

View File

@ -84,6 +84,9 @@ open class ButtonElement(
forceApply() forceApply()
} }
override val canFocus: Boolean
get() = !disabled
init { init {
size = textElement.size + Vec2i(TEXT_PADDING * 2, TEXT_PADDING * 2) size = textElement.size + Vec2i(TEXT_PADDING * 2, TEXT_PADDING * 2)

View File

@ -31,7 +31,6 @@ abstract class Menu(
val preferredElementWidth: Int = 150, val preferredElementWidth: Int = 150,
) : Screen(guiRenderer) { ) : Screen(guiRenderer) {
private val elements: MutableList<Element> = mutableListOf() private val elements: MutableList<Element> = mutableListOf()
private var focusedIndex: Int = -1
private var maxElementWidth = -1 private var maxElementWidth = -1
private var totalHeight = -1 private var totalHeight = -1
@ -88,7 +87,6 @@ abstract class Menu(
if (activeElement != element) { if (activeElement != element) {
activeElement?.onMouseLeave() activeElement?.onMouseLeave()
element?.onMouseEnter(delta) element?.onMouseEnter(delta)
focusedIndex = elements.indexOf(element)
activeElement = element activeElement = element
return return
} }
@ -146,17 +144,35 @@ abstract class Menu(
for (element in elements) { for (element in elements) {
element.onClose() element.onClose()
} }
focusedIndex = -1 activeElement?.onMouseLeave()
activeElement = null
} }
override fun onSpecialKey(key: InputSpecialKey, type: KeyChangeTypes) { override fun onSpecialKey(key: InputSpecialKey, type: KeyChangeTypes) {
super.onSpecialKey(key, type) super.onSpecialKey(key, type)
if (type != KeyChangeTypes.RELEASE && key == InputSpecialKey.KEY_TAB) { if (type != KeyChangeTypes.RELEASE && key == InputSpecialKey.KEY_TAB) {
focusedIndex++ var element: Element?
if (focusedIndex >= elements.size) { var initialIndex = elements.indexOf(activeElement)
focusedIndex = 0 if (initialIndex == -1) {
initialIndex = 0
}
var index = initialIndex
while (true) {
index++
if (index >= elements.size) {
index = 0
}
if (index == initialIndex) {
return
}
element = elements.getOrNull(index) ?: return
if (element.canFocus) {
break
}
}
if (element == null) {
return
} }
val element = elements.getOrNull(focusedIndex) ?: return
activeElement?.onMouseLeave() activeElement?.onMouseLeave()
element.onMouseEnter(Vec2i.EMPTY) element.onMouseEnter(Vec2i.EMPTY)