spinner filler with Meta
Vladimir Bauer
2 years ago
| 3 | 3 | "io" |
| 4 | 4 | "strings" |
| 5 | 5 | |
| 6 | "github.com/acarl005/stripansi" | |
| 7 | 6 | "github.com/mattn/go-runewidth" |
| 8 | 7 | "github.com/vbauerster/mpb/v8/decor" |
| 9 | 8 | "github.com/vbauerster/mpb/v8/internal" |
| 14 | 13 | positionRight |
| 15 | 14 | ) |
| 16 | 15 | |
| 16 | var defaultSpinnerStyle = []string{"⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"} | |
| 17 | ||
| 17 | 18 | // SpinnerStyleComposer interface. |
| 18 | 19 | type SpinnerStyleComposer interface { |
| 19 | 20 | BarFillerBuilder |
| 20 | 21 | PositionLeft() SpinnerStyleComposer |
| 21 | 22 | PositionRight() SpinnerStyleComposer |
| 23 | Meta(func(string) string) SpinnerStyleComposer | |
| 22 | 24 | } |
| 23 | 25 | |
| 24 | 26 | type sFiller struct { |
| 27 | position uint | |
| 25 | 28 | count uint |
| 26 | position uint | |
| 27 | 29 | frames []string |
| 30 | meta func(string) string | |
| 28 | 31 | } |
| 29 | 32 | |
| 30 | 33 | type spinnerStyle struct { |
| 31 | 34 | position uint |
| 32 | 35 | frames []string |
| 36 | meta func(string) string | |
| 33 | 37 | } |
| 34 | 38 | |
| 35 | 39 | // SpinnerStyle constructs default spinner style which can be altered via |
| 36 | 40 | // SpinnerStyleComposer interface. |
| 37 | 41 | func SpinnerStyle(frames ...string) SpinnerStyleComposer { |
| 38 | ss := new(spinnerStyle) | |
| 42 | ss := &spinnerStyle{ | |
| 43 | meta: func(s string) string { | |
| 44 | return s | |
| 45 | }, | |
| 46 | } | |
| 39 | 47 | if len(frames) != 0 { |
| 40 | ss.frames = append(ss.frames, frames...) | |
| 48 | ss.frames = frames | |
| 41 | 49 | } else { |
| 42 | ss.frames = []string{"⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"} | |
| 50 | ss.frames = defaultSpinnerStyle | |
| 43 | 51 | } |
| 44 | 52 | return ss |
| 45 | 53 | } |
| 54 | 62 | return s |
| 55 | 63 | } |
| 56 | 64 | |
| 65 | func (s *spinnerStyle) Meta(fn func(string) string) SpinnerStyleComposer { | |
| 66 | s.meta = fn | |
| 67 | return s | |
| 68 | } | |
| 69 | ||
| 57 | 70 | func (s *spinnerStyle) Build() BarFiller { |
| 58 | 71 | sf := &sFiller{ |
| 59 | 72 | position: s.position, |
| 60 | 73 | frames: s.frames, |
| 74 | meta: s.meta, | |
| 61 | 75 | } |
| 62 | 76 | return sf |
| 63 | 77 | } |
| 66 | 80 | width := internal.CheckRequestedWidth(stat.RequestedWidth, stat.AvailableWidth) |
| 67 | 81 | |
| 68 | 82 | frame := s.frames[s.count%uint(len(s.frames))] |
| 69 | frameWidth := runewidth.StringWidth(stripansi.Strip(frame)) | |
| 83 | frameWidth := runewidth.StringWidth(frame) | |
| 84 | frame = s.meta(frame) | |
| 70 | 85 | |
| 71 | 86 | if width < frameWidth { |
| 72 | 87 | return nil |