Codebase list golang-github-vbauerster-mpb / 5735901
refactoring filler spinner determine position at spinnerStyle Build time Vladimir Bauer 2 years ago
1 changed file(s) with 23 addition(s) and 22 deletion(s). Raw diff Collapse all Expand all
00 package mpb
11
22 import (
3 "fmt"
34 "io"
45 "strings"
56
2425 }
2526
2627 type sFiller struct {
27 position uint
28 frames []string
2829 count uint
29 frames []string
3030 meta func(string) string
31 position func(string, int) string
3132 }
3233
3334 type spinnerStyle struct {
4041 // SpinnerStyleComposer interface.
4142 func SpinnerStyle(frames ...string) SpinnerStyleComposer {
4243 ss := spinnerStyle{
43 meta: func(s string) string {
44 return s
45 },
44 meta: func(s string) string { return s },
4645 }
4746 if len(frames) != 0 {
4847 ss.frames = frames
6968
7069 func (s spinnerStyle) Build() BarFiller {
7170 sf := &sFiller{
72 position: s.position,
73 frames: s.frames,
74 meta: s.meta,
71 frames: s.frames,
72 meta: s.meta,
73 }
74 switch s.position {
75 case positionLeft:
76 sf.position = func(frame string, padWidth int) string {
77 return fmt.Sprint(frame, strings.Repeat(" ", padWidth))
78 }
79 case positionRight:
80 sf.position = func(frame string, padWidth int) string {
81 return fmt.Sprint(strings.Repeat(" ", padWidth), frame)
82 }
83 default:
84 sf.position = func(frame string, padWidth int) string {
85 return fmt.Sprint(strings.Repeat(" ", padWidth/2), frame, strings.Repeat(" ", padWidth/2+padWidth%2))
86 }
7587 }
7688 return sf
7789 }
7890
79 func (s *sFiller) Fill(w io.Writer, stat decor.Statistics) (err error) {
91 func (s *sFiller) Fill(w io.Writer, stat decor.Statistics) error {
8092 width := internal.CheckRequestedWidth(stat.RequestedWidth, stat.AvailableWidth)
81
8293 frame := s.frames[s.count%uint(len(s.frames))]
8394 frameWidth := runewidth.StringWidth(frame)
84 frame = s.meta(frame)
95 s.count++
8596
8697 if width < frameWidth {
8798 return nil
8899 }
89100
90 rest := width - frameWidth
91 switch s.position {
92 case positionLeft:
93 _, err = io.WriteString(w, frame+strings.Repeat(" ", rest))
94 case positionRight:
95 _, err = io.WriteString(w, strings.Repeat(" ", rest)+frame)
96 default:
97 str := strings.Repeat(" ", rest/2) + frame + strings.Repeat(" ", rest/2+rest%2)
98 _, err = io.WriteString(w, str)
99 }
100 s.count++
101 _, err := io.WriteString(w, s.position(s.meta(frame), width-frameWidth))
101102 return err
102103 }