forked from quantum/gonsole
-
Notifications
You must be signed in to change notification settings - Fork 0
/
checkbox.go
81 lines (65 loc) · 1.43 KB
/
checkbox.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
74
75
76
77
78
79
80
81
package gonsole
import "github.com/nsf/termbox-go"
type Checkbox struct {
BaseControl
text string
checked bool
onChange func(checked bool)
}
func NewCheckbox(win AppWindow, parent Container, id string) *Checkbox {
checkbox := &Checkbox{}
checkbox.Init(win, parent, id, "checkbox")
checkbox.SetFocusable(true)
parent.AddControl(checkbox)
return checkbox
}
func (c *Checkbox) Text() string {
return c.text
}
func (c *Checkbox) SetText(text string) {
c.text = text
}
func (c *Checkbox) Checked() bool {
return c.checked
}
func (c *Checkbox) SeChecked(checked bool) {
c.checked = checked
}
func (c *Checkbox) OnChange(handler func(checked bool)) {
c.onChange = handler
}
func (c *Checkbox) Repaint() {
if !c.Dirty() {
return
}
c.BaseControl.Repaint()
var icon string
if c.checked {
icon = "☑"
} else {
icon = "☐"
}
t := c.Theme()
fg, bg := t.ColorTermbox("fg"), t.ColorTermbox("bg")
contentBox := c.ContentBox()
DrawTextSimple(icon, false, contentBox, fg, bg)
DrawTextBox(c.text, contentBox.Minus(Sides{Left: 2}), fg, bg)
}
func (chk *Checkbox) ParseEvent(ev *termbox.Event) (handled, repaint bool) {
switch ev.Type {
case termbox.EventKey:
switch ev.Key {
case termbox.KeyEnter:
fallthrough
case termbox.KeySpace:
chk.checked = !chk.checked
if chk.onChange != nil {
chk.onChange(chk.checked)
}
return true, true
}
case termbox.EventError:
panic(ev.Err)
}
return false, false
}