-
Notifications
You must be signed in to change notification settings - Fork 131
Expand file tree
/
Copy pathbar_filler_spinner.go
More file actions
100 lines (85 loc) · 2.36 KB
/
Copy pathbar_filler_spinner.go
File metadata and controls
100 lines (85 loc) · 2.36 KB
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
package mpb
import (
"io"
"strings"
"github.com/mattn/go-runewidth"
"github.com/vbauerster/mpb/v8/decor"
"github.com/vbauerster/mpb/v8/internal"
)
const (
positionLeft = 1 + iota
positionRight
)
var spinnerStyleComposer = SpinnerStyleComposer{
frames: []string{"⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"},
}
type spinnerFiller struct {
frames []string
count uint
meta func(string) string
position func(string, int) string
}
// SpinnerStyleComposer is a builder which provides methods to build custom BarFiller.
// Call SpinnerStyle to construct a new one.
type SpinnerStyleComposer struct {
position uint
frames []string
meta func(string) string
}
// SpinnerStyle constructs default SpinnerStyleComposer which implements
// BarFillerBuilder interface.
func SpinnerStyle(frames ...string) SpinnerStyleComposer {
if len(frames) == 0 {
return spinnerStyleComposer
}
return SpinnerStyleComposer{frames: frames}
}
func (s SpinnerStyleComposer) PositionLeft() SpinnerStyleComposer {
s.position = positionLeft
return s
}
func (s SpinnerStyleComposer) PositionRight() SpinnerStyleComposer {
s.position = positionRight
return s
}
func (s SpinnerStyleComposer) Meta(fn func(string) string) SpinnerStyleComposer {
s.meta = fn
return s
}
func (s SpinnerStyleComposer) ToBuilder() BarFillerBuilder {
return s
}
func (s SpinnerStyleComposer) Build() BarFiller {
sf := &spinnerFiller{frames: s.frames}
switch s.position {
case positionLeft:
sf.position = func(frame string, padWidth int) string {
return frame + strings.Repeat(" ", padWidth)
}
case positionRight:
sf.position = func(frame string, padWidth int) string {
return strings.Repeat(" ", padWidth) + frame
}
default:
sf.position = func(frame string, padWidth int) string {
return strings.Repeat(" ", padWidth/2) + frame + strings.Repeat(" ", padWidth/2+padWidth%2)
}
}
if s.meta != nil {
sf.meta = s.meta
} else {
sf.meta = func(s string) string { return s }
}
return sf
}
func (s *spinnerFiller) Fill(w io.Writer, stat decor.Statistics) error {
width := internal.CheckRequestedWidth(stat.RequestedWidth, stat.AvailableWidth)
frame := s.frames[s.count%uint(len(s.frames))]
frameWidth := runewidth.StringWidth(frame)
s.count++
if width < frameWidth {
return nil
}
_, err := io.WriteString(w, s.position(s.meta(frame), width-frameWidth))
return err
}