/
widget.go
97 lines (80 loc) · 1.79 KB
/
widget.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package widget
import (
"fmt"
"strconv"
"github.com/icecream78/gomodoro/pomodoro"
"github.com/cheggaaa/pb/v3"
)
const (
ZeroedTime int = 0
ZeroedStepper int = 1
DefaultShowTime int = 100
)
// NewBar returns new copy of widget that is shown in terminal
func NewBar(template string) *Widget {
w := Widget{
template: template,
showTime: DefaultShowTime,
}
return &w
}
type Widget struct {
template string
showTime int
bar *pb.ProgressBar
}
func (w *Widget) Tick() {
w.bar.Increment()
}
func (w *Widget) InitBar(barTime int) {
w.bar = pb.ProgressBarTemplate(w.template).Start(barTime)
return
}
func (w *Widget) Update(state *pomodoro.State) {
if state.Event == pomodoro.PreStepHook {
w.InitBar(state.TotalTime)
return
}
if state.Event == pomodoro.Progress {
w.bar.Increment()
ts := w.renderTimer(state.Progress, state.IsEnding)
ss := w.formatSteps(state.Step, state.TotalStep)
w.bar.Set("timer", ts)
w.bar.Set("steps", ss)
}
// manual calling write method for bar rerender
if state.Event == pomodoro.PostStepHook {
w.bar.Finish()
}
}
func (w *Widget) getTimerColorFunc(now int, isEnding bool) colorFunc {
if now == 0 {
return doneColor
} else if isEnding {
return finishingColor
} else {
return progressColor
}
}
func (w *Widget) renderTimer(time int, isEnding bool) string {
cf := w.getTimerColorFunc(time, isEnding)
res := cf(w.formatTime(time))
return res
}
func (w *Widget) formatTime(time int) string {
min, sec := getMinutesSeconds(time)
if min == 0 && sec == 0 {
return "Finished!"
}
return fmt.Sprintf(
"%s:%s",
padLeft(strconv.Itoa(min), "0", 2),
padLeft(strconv.Itoa(sec), "0", 2),
)
}
func (w *Widget) formatSteps(current int, total int) string {
if total == 1 {
return ""
}
return fmt.Sprintf("%d/%d", current, total)
}