last_light/game/ui/simple_button.go

102 lines
2.2 KiB
Go
Raw Normal View History

2024-04-24 17:11:33 +03:00
package ui
import (
2024-05-06 20:43:35 +03:00
"mvvasilev/last_light/engine"
2024-04-24 17:11:33 +03:00
"strings"
"unicode/utf8"
"github.com/gdamore/tcell/v2"
"github.com/gdamore/tcell/v2/views"
"github.com/google/uuid"
)
type UISimpleButton struct {
id uuid.UUID
isHighlighted bool
2024-05-06 20:43:35 +03:00
text *engine.Text
2024-04-24 17:11:33 +03:00
selectHandler func()
unhighlightedStyle tcell.Style
highlightedStyle tcell.Style
}
func CreateSimpleButton(x, y int, text string, unhighlightedStyle, highlightedStyle tcell.Style, onSelect func()) *UISimpleButton {
2024-04-24 17:11:33 +03:00
sb := new(UISimpleButton)
sb.id = uuid.New()
2024-05-06 20:43:35 +03:00
sb.text = engine.CreateText(x, y, int(utf8.RuneCountInString(text)), 1, text, unhighlightedStyle)
2024-04-24 17:11:33 +03:00
sb.isHighlighted = false
sb.selectHandler = onSelect
sb.highlightedStyle = highlightedStyle
sb.unhighlightedStyle = unhighlightedStyle
return sb
}
func (sb *UISimpleButton) Select() {
sb.selectHandler()
}
func (sb *UISimpleButton) OnSelect(f func()) {
sb.selectHandler = f
}
func (sb *UISimpleButton) IsHighlighted() bool {
return sb.isHighlighted
}
func (sb *UISimpleButton) Highlight() {
sb.isHighlighted = true
newContent := "[ " + sb.text.Content() + " ]"
2024-05-06 20:43:35 +03:00
sb.text = engine.CreateText(
int(sb.Position().X()-2), int(sb.Position().Y()),
int(utf8.RuneCountInString(newContent)), 1,
2024-04-24 17:11:33 +03:00
newContent,
sb.highlightedStyle,
)
}
func (sb *UISimpleButton) Unhighlight() {
sb.isHighlighted = false
content := strings.Trim(sb.text.Content(), " ]")
content = strings.Trim(content, "[ ")
contentLen := utf8.RuneCountInString(content)
2024-05-06 20:43:35 +03:00
sb.text = engine.CreateText(
int(sb.Position().X()+2), int(sb.Position().Y()),
int(contentLen), 1,
2024-04-24 17:11:33 +03:00
content,
sb.unhighlightedStyle,
)
}
func (sb *UISimpleButton) SetHighlighted(highlighted bool) {
sb.isHighlighted = highlighted
}
func (sb *UISimpleButton) UniqueId() uuid.UUID {
return sb.id
}
func (sb *UISimpleButton) MoveTo(x int, y int) {
2024-05-06 20:43:35 +03:00
sb.text = engine.CreateText(x, y, int(utf8.RuneCountInString(sb.text.Content())), 1, sb.text.Content(), sb.highlightedStyle)
2024-04-24 17:11:33 +03:00
}
2024-05-06 21:47:20 +03:00
func (sb *UISimpleButton) Position() engine.Position {
2024-04-24 17:11:33 +03:00
return sb.text.Position()
}
2024-05-06 21:47:20 +03:00
func (sb *UISimpleButton) Size() engine.Size {
2024-04-24 17:11:33 +03:00
return sb.text.Size()
}
func (sb *UISimpleButton) Draw(v views.View) {
sb.text.Draw(v)
}
func (sb *UISimpleButton) Input(e *tcell.EventKey) {
}