/
loader.go
69 lines (59 loc) · 1.51 KB
/
loader.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
package ansi
import (
"fmt"
"time"
)
// cleanup clears the line and redisplays the cursor
func cleanup() {
fmt.Print(EraseLine(2))
fmt.Print(ShowCursor())
}
// LoaderControl holds internal data for the loader
type LoaderControl struct {
anim []string // The animation sprite list
value string // The label value
cursor int // The current position of the animation
max int // The length of the animation list
ticker *time.Ticker // Pointer to the ticker instance
done chan bool // Channel used to stop the loader
}
// Start will start the loader
func (loader *LoaderControl) Start() {
go func() {
for {
select {
case <-loader.done:
return
case <-loader.ticker.C:
fmt.Print(HideCursor())
fmt.Print(EraseLine(2))
fmt.Print(CursorStart(1))
if loader.cursor >= loader.max {
loader.cursor = 0
}
fmt.Print(loader.anim[loader.cursor] + " " + loader.value)
loader.cursor++
}
}
}()
}
// Stop will stop the loader
func (loader *LoaderControl) Stop() {
loader.done <- true
cleanup()
}
// SetValue will set a new value for the label
func (loader *LoaderControl) SetValue(value string) {
loader.value = value
}
// Loader creates a new loader with the given `anim` that animates at the specified `speed`
func Loader(anim []string, speed int) *LoaderControl {
return &LoaderControl{
cursor: 0,
anim: anim,
value: "",
max: len(anim),
ticker: time.NewTicker(time.Millisecond * time.Duration(speed)),
done: make(chan bool),
}
}