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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
|
package slider
import (
"fmt"
"github.com/charmbracelet/bubbles/progress"
tea "github.com/charmbracelet/bubbletea"
)
const (
// Global Keystrokes for sliders
setMinKey = "i" // i -> Initialise
setMaxKey = "I"
bigDecKey = "h" // vim left
smallDecKey = "H"
bigIncKey = "l" // vim right
smallIncKey = "L"
)
func Keystrokes() []string {
return []string{
setMinKey, setMaxKey, bigIncKey, bigDecKey, smallIncKey, smallDecKey,
}
}
type Slider struct {
name string
val int
max int
bar progress.Model
loaded bool
options []progress.Option
}
func (s Slider) Set(val int) (tea.Model, tea.Cmd) {
s.val = val
if s.val > s.max {
s.val = s.max
}
if s.val < 0 {
s.val = 0
}
return s, s.bar.SetPercent(float64(s.val) / float64(s.max))
}
func (s Slider) Inc(val int) (tea.Model, tea.Cmd) {
return s.Set(s.val + val)
}
func (s Slider) Dec(val int) (tea.Model, tea.Cmd) {
return s.Set(s.val - val)
}
func (s Slider) View() string {
return s.bar.View() + fmt.Sprintf(" (%d)", s.val)
}
func (s Slider) Animate(msg tea.Msg) (tea.Model, tea.Cmd) {
progressModel, cmd := s.bar.Update(msg)
s.bar = progressModel.(progress.Model)
return s, cmd
}
// Implement tea.Model interface {{{
func (s Slider) Init() tea.Cmd {
return s.bar.Init()
}
func New(name string, v int, maxV int, opt ...progress.Option) *Slider {
opt = append(opt, progress.WithoutPercentage())
return &Slider{name: name, max: maxV, val: v, options: opt}
}
func (s Slider) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.KeyMsg:
switch msg.String() {
case bigIncKey:
return s.Inc(25)
case smallIncKey:
return s.Inc(1)
case bigDecKey:
return s.Dec(25)
case smallDecKey:
return s.Dec(1)
case setMinKey:
return s.Set(0)
case setMaxKey:
return s.Set(s.max)
default:
return s, tea.Quit
}
case tea.WindowSizeMsg:
if s.bar.Width != msg.Width && !s.loaded {
s.loaded = true
s.bar = progress.New(s.options...)
return s.Set(s.val)
}
case progress.FrameMsg:
return s.Animate(msg)
}
return s, nil
}
// }}}
|