Skip to content

Commit

Permalink
add enable/disable toggle (#144)
Browse files Browse the repository at this point in the history
  • Loading branch information
jrslv authored Jul 31, 2022
1 parent ea7e799 commit 329c376
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
21 changes: 20 additions & 1 deletion spinner.go
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,7 @@ type Spinner struct {
color func(a ...interface{}) string // default color is white
Writer io.Writer // to make testing better, exported so users have access. Use `WithWriter` to update after initialization.
active bool // active holds the state of the spinner
enabled bool // indicates whether the spinner is enabled or not
stopChan chan struct{} // stopChan is a channel used to stop the indicator
HideCursor bool // hideCursor determines if the cursor is visible
PreUpdate func(s *Spinner) // will be triggered before every spinner update
Expand All @@ -202,6 +203,7 @@ func New(cs []string, d time.Duration, options ...Option) *Spinner {
Writer: color.Output,
stopChan: make(chan struct{}, 1),
active: false,
enabled: true,
HideCursor: true,
}

Expand Down Expand Up @@ -271,10 +273,27 @@ func (s *Spinner) Active() bool {
return s.active
}

// Enabled returns whether or not the spinner is enabled.
func (s *Spinner) Enabled() bool {
return s.enabled
}

// Enable enables and restarts the spinner
func (s *Spinner) Enable() {
s.enabled = true
s.Restart()
}

// Disable stops and disables the spinner
func (s *Spinner) Disable() {
s.enabled = false
s.Stop()
}

// Start will start the indicator.
func (s *Spinner) Start() {
s.mu.Lock()
if s.active || !isRunningInTerminal() {
if s.active || !s.enabled || !isRunningInTerminal() {
s.mu.Unlock()
return
}
Expand Down
22 changes: 22 additions & 0 deletions spinner_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,28 @@ func TestRestart(t *testing.T) {
}
}

func TestDisable(t *testing.T) {
s, _ := withOutput(CharSets[4], 100*time.Millisecond)

s.Start()
time.Sleep(150 * time.Millisecond)
if !s.Enabled() {
t.Error("expected enabled spinner after startup")
}
time.Sleep(150 * time.Millisecond)
s.Disable()
time.Sleep(150 * time.Millisecond)
if s.Enabled() {
t.Error("expected disabling the spinner works")
}
time.Sleep(150 * time.Millisecond)
s.Enable()
time.Sleep(150 * time.Millisecond)
if !s.Enabled() {
t.Error("expected enabling the spinner works")
}
}

// TestHookFunctions will verify that hook functions works as expected
func TestHookFunctions(t *testing.T) {
if !isatty.IsTerminal(os.Stdout.Fd()) {
Expand Down

0 comments on commit 329c376

Please sign in to comment.