aboutsummaryrefslogtreecommitdiff
path: root/vendor/github.com/vbauerster/mpb/v7/bar_filler_spinner.go
blob: 58ae1c532838dd6bc2ac7d9b48c349ae615d3ed2 (plain)
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
package mpb

import (
	"io"
	"strings"

	"github.com/acarl005/stripansi"
	"github.com/mattn/go-runewidth"
	"github.com/vbauerster/mpb/v7/decor"
	"github.com/vbauerster/mpb/v7/internal"
)

const (
	positionLeft = 1 + iota
	positionRight
)

// SpinnerStyleComposer interface.
type SpinnerStyleComposer interface {
	BarFillerBuilder
	PositionLeft() SpinnerStyleComposer
	PositionRight() SpinnerStyleComposer
}

type sFiller struct {
	count    uint
	position uint
	frames   []string
}

type spinnerStyle struct {
	position uint
	frames   []string
}

// SpinnerStyle constructs default spinner style which can be altered via
// SpinnerStyleComposer interface.
func SpinnerStyle(frames ...string) SpinnerStyleComposer {
	ss := new(spinnerStyle)
	if len(frames) != 0 {
		ss.frames = append(ss.frames, frames...)
	} else {
		ss.frames = []string{"⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"}
	}
	return ss
}

func (s *spinnerStyle) PositionLeft() SpinnerStyleComposer {
	s.position = positionLeft
	return s
}

func (s *spinnerStyle) PositionRight() SpinnerStyleComposer {
	s.position = positionRight
	return s
}

func (s *spinnerStyle) Build() BarFiller {
	sf := &sFiller{
		position: s.position,
		frames:   s.frames,
	}
	return sf
}

func (s *sFiller) Fill(w io.Writer, width int, stat decor.Statistics) {
	width = internal.CheckRequestedWidth(width, stat.AvailableWidth)

	frame := s.frames[s.count%uint(len(s.frames))]
	frameWidth := runewidth.StringWidth(stripansi.Strip(frame))

	if width < frameWidth {
		return
	}

	rest := width - frameWidth
	switch s.position {
	case positionLeft:
		io.WriteString(w, frame+strings.Repeat(" ", rest))
	case positionRight:
		io.WriteString(w, strings.Repeat(" ", rest)+frame)
	default:
		str := strings.Repeat(" ", rest/2) + frame + strings.Repeat(" ", rest/2+rest%2)
		io.WriteString(w, str)
	}
	s.count++
}