Add visibility methods to widgets

This commit is contained in:
Trevor Slocum 2023-10-24 19:35:38 -07:00
parent dd561eaee1
commit 7515991afc
3 changed files with 36 additions and 3 deletions

15
box.go
View file

@ -8,15 +8,17 @@ import (
)
type Box struct {
rect image.Rectangle
rect image.Rectangle
children []Widget
visible bool
sync.Mutex
}
func NewBox() *Box {
return &Box{}
return &Box{
visible: true,
}
}
func (b *Box) Rect() image.Rectangle {
@ -37,6 +39,13 @@ func (b *Box) SetFocus(focus bool) bool {
return false
}
func (b *Box) SetVisible(visible bool) {
b.visible = visible
}
func (b *Box) Visible() bool {
return b.visible
}
func (b *Box) Focus() bool {
return false
}

22
game.go
View file

@ -110,7 +110,12 @@ func getWidgetAt(w Widget, cursor image.Point) Widget {
if !cursor.In(w.Rect()) {
return nil
}
for _, child := range w.Children() {
if !child.Visible() {
continue
}
if cursor.In(child.Rect()) {
result := getWidgetAt(child, cursor)
if result != nil {
@ -118,13 +123,22 @@ func getWidgetAt(w Widget, cursor image.Point) Widget {
}
}
}
return w
}
func update(w Widget, cursor image.Point, pressed bool, clicked bool, mouseHandled bool, keyboardHandled bool) (bool, bool, error) {
if !w.Visible() {
return mouseHandled, keyboardHandled, nil
}
var err error
children := w.Children()
for _, child := range children {
if !child.Visible() {
continue
}
mouseHandled, keyboardHandled, err = update(child, cursor, pressed, clicked, mouseHandled, keyboardHandled)
if err != nil {
return false, false, err
@ -159,6 +173,10 @@ func Draw(screen *ebiten.Image) error {
}
func draw(w Widget, screen *ebiten.Image) error {
if !w.Visible() {
return nil
}
err := w.Draw(screen)
if err != nil {
return fmt.Errorf("failed to draw widget: %s", err)
@ -166,6 +184,10 @@ func draw(w Widget, screen *ebiten.Image) error {
children := w.Children()
for _, child := range children {
if !child.Visible() {
continue
}
err = draw(child, screen)
if err != nil {
return fmt.Errorf("failed to draw widget: %s", err)

View file

@ -10,6 +10,8 @@ type Widget interface {
Rect() image.Rectangle
SetRect(r image.Rectangle)
SetFocus(focus bool) (accept bool)
SetVisible(visible bool)
Visible() bool
HandleMouse(cursor image.Point, pressed bool, clicked bool) (handled bool, err error)
HandleKeyboard() (handled bool, err error)
HandleKeyboardEvent(ebiten.Key, rune) (handled bool, err error)