krampus19/alui/menu.go

86 lines
1.5 KiB
Go
Raw Normal View History

2019-12-27 12:18:33 +00:00
package alui
import (
"opslag.de/schobers/allg5"
)
type Menu struct {
Column
2019-12-27 12:18:33 +00:00
OnEscape func()
2019-12-27 12:18:33 +00:00
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)
2019-12-27 12:18:33 +00:00
}
func (m *Menu) Handle(e allg5.Event) {
m.Column.Handle(e)
2019-12-27 12:18:33 +00:00
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()
}
}
2019-12-27 12:18:33 +00:00
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
}
}