forked from marcusolsson/tui-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
button.go
73 lines (61 loc) · 1.35 KB
/
button.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package tui
import (
"image"
"strings"
)
var _ Widget = &Button{}
// Button is a widget that can be activated to perform some action, or to
// answer a question.
type Button struct {
WidgetBase
text string
onActivated func(*Button)
}
// NewButton returns a new Button with the given text as the label.
func NewButton(text string) *Button {
return &Button{
text: text,
}
}
// Draw draws the button.
func (b *Button) Draw(p *Painter) {
style := "button"
if b.IsFocused() {
style += ".focused"
}
p.WithStyle(style, func(p *Painter) {
lines := strings.Split(b.text, "\n")
for i, line := range lines {
p.FillRect(0, i, b.Size().X, 1)
p.DrawText(0, i, line)
}
})
}
// SizeHint returns the recommended size hint for the button.
func (b *Button) SizeHint() image.Point {
if len(b.text) == 0 {
return b.MinSizeHint()
}
var size image.Point
lines := strings.Split(b.text, "\n")
for _, line := range lines {
if w := stringWidth(line); w > size.X {
size.X = w
}
}
size.Y = len(lines)
return size
}
// OnKeyEvent handles keys events.
func (b *Button) OnKeyEvent(ev KeyEvent) {
if !b.IsFocused() {
return
}
if ev.Key == KeyEnter && b.onActivated != nil {
b.onActivated(b)
}
}
// OnActivated allows a custom function to be run whenever the button is activated.
func (b *Button) OnActivated(fn func(b *Button)) {
b.onActivated = fn
}