krampus19/alui/menu.go
Sander Schobers 8ef4e4ea3a Changed movement animation again.
Movement starts on KeyDownEvent instead of KeyCharEvent.
2019-12-29 10:15:32 +01:00

86 lines
1.5 KiB
Go

package alui
import (
"opslag.de/schobers/allg5"
)
type Menu struct {
Column
OnEscape func()
active int
buttons []*Button
}
func NewMenu() *Menu {
m := &Menu{}
m.Init()
return m
}
func (m *Menu) Activate(i int) {
if len(m.buttons) == 0 || i < 0 {
return
}
m.active = i % len(m.buttons)
}
func (m *Menu) Add(text string, onClick func()) {
idx := len(m.buttons)
button := &Button{Text: text, TextAlign: allg5.AlignCenter}
button.OnClick = onClick
button.OnEnter = func() {
m.updateActiveButton(idx)
}
if idx == 0 {
button.Over = true
}
m.buttons = append(m.buttons, button)
m.AddChild(button)
}
func (m *Menu) Handle(e allg5.Event) {
m.Column.Handle(e)
if len(m.buttons) == 0 {
return
}
switch e := e.(type) {
case *allg5.KeyDownEvent:
switch e.KeyCode {
case allg5.KeyEscape:
if onEscape := m.OnEscape; onEscape != nil {
onEscape()
}
}
case *allg5.KeyCharEvent:
switch e.KeyCode {
case allg5.KeyDown:
m.updateActiveButton((m.active + 1) % len(m.buttons))
case allg5.KeyUp:
m.updateActiveButton((m.active + len(m.buttons) - 1) % len(m.buttons))
case allg5.KeyEnter:
if onClick := m.buttons[m.active].OnClick; onClick != nil {
onClick()
}
}
case *allg5.MouseMoveEvent:
for i, btn := range m.buttons {
if btn.Over {
m.updateActiveButton(i)
break
}
}
m.updateActiveButton(m.active)
}
}
func (m *Menu) updateActiveButton(active int) {
m.active = active
for i, btn := range m.buttons {
btn.Over = i == m.active
}
}