Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add enable/disable toggle #144

Merged
merged 1 commit into from Jul 31, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
21 changes: 20 additions & 1 deletion spinner.go
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
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