-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathcheckbox.go
74 lines (64 loc) · 1.29 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
package main
import (
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
)
const (
off int = iota
on
title
)
// A Checkbox, when it state has changed the [CheckboxUpdated] will be emitted,
// use Id to distinguish checkboxes.
type Checkbox struct {
id int
style []lipgloss.Style
text []string
state int
}
type CheckboxUpdated struct {
Id int
On bool
}
func NewCheckbox(
id int, titleText, onText, offText string,
titleStyle, onStyle, offStyle lipgloss.Style) Checkbox {
return Checkbox{
id: id,
text: []string{offText, onText, titleText},
style: []lipgloss.Style{offStyle, onStyle, titleStyle},
}
}
func (c Checkbox) View() string {
return lipgloss.JoinHorizontal(
lipgloss.Top,
c.style[title].Render(c.text[title]),
c.style[c.state].Render(c.text[c.state]),
)
}
func (c *Checkbox) IsOn() bool {
return c.state == on
}
func (c *Checkbox) SetOn() {
c.state = on
}
func (c *Checkbox) SetOff() {
c.state = off
}
func (c Checkbox) Update(msg tea.Msg) (Checkbox, tea.Cmd) {
switch msg := msg.(type) {
case tea.KeyMsg:
switch msg.Type {
case tea.KeySpace: // toggle checkbox
if c.state == on {
c.state = off
} else {
c.state = on
}
}
}
cmd := func() tea.Msg {
return CheckboxUpdated{Id: c.id, On: c.IsOn()}
}
return c, cmd
}