Skip to content

Commit 329c376

Browse files
authored
add enable/disable toggle (#144)
1 parent ea7e799 commit 329c376

File tree

2 files changed

+42
-1
lines changed

2 files changed

+42
-1
lines changed

spinner.go

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,7 @@ type Spinner struct {
186186
color func(a ...interface{}) string // default color is white
187187
Writer io.Writer // to make testing better, exported so users have access. Use `WithWriter` to update after initialization.
188188
active bool // active holds the state of the spinner
189+
enabled bool // indicates whether the spinner is enabled or not
189190
stopChan chan struct{} // stopChan is a channel used to stop the indicator
190191
HideCursor bool // hideCursor determines if the cursor is visible
191192
PreUpdate func(s *Spinner) // will be triggered before every spinner update
@@ -202,6 +203,7 @@ func New(cs []string, d time.Duration, options ...Option) *Spinner {
202203
Writer: color.Output,
203204
stopChan: make(chan struct{}, 1),
204205
active: false,
206+
enabled: true,
205207
HideCursor: true,
206208
}
207209

@@ -271,10 +273,27 @@ func (s *Spinner) Active() bool {
271273
return s.active
272274
}
273275

276+
// Enabled returns whether or not the spinner is enabled.
277+
func (s *Spinner) Enabled() bool {
278+
return s.enabled
279+
}
280+
281+
// Enable enables and restarts the spinner
282+
func (s *Spinner) Enable() {
283+
s.enabled = true
284+
s.Restart()
285+
}
286+
287+
// Disable stops and disables the spinner
288+
func (s *Spinner) Disable() {
289+
s.enabled = false
290+
s.Stop()
291+
}
292+
274293
// Start will start the indicator.
275294
func (s *Spinner) Start() {
276295
s.mu.Lock()
277-
if s.active || !isRunningInTerminal() {
296+
if s.active || !s.enabled || !isRunningInTerminal() {
278297
s.mu.Unlock()
279298
return
280299
}

spinner_test.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,28 @@ func TestRestart(t *testing.T) {
132132
}
133133
}
134134

135+
func TestDisable(t *testing.T) {
136+
s, _ := withOutput(CharSets[4], 100*time.Millisecond)
137+
138+
s.Start()
139+
time.Sleep(150 * time.Millisecond)
140+
if !s.Enabled() {
141+
t.Error("expected enabled spinner after startup")
142+
}
143+
time.Sleep(150 * time.Millisecond)
144+
s.Disable()
145+
time.Sleep(150 * time.Millisecond)
146+
if s.Enabled() {
147+
t.Error("expected disabling the spinner works")
148+
}
149+
time.Sleep(150 * time.Millisecond)
150+
s.Enable()
151+
time.Sleep(150 * time.Millisecond)
152+
if !s.Enabled() {
153+
t.Error("expected enabling the spinner works")
154+
}
155+
}
156+
135157
// TestHookFunctions will verify that hook functions works as expected
136158
func TestHookFunctions(t *testing.T) {
137159
if !isatty.IsTerminal(os.Stdout.Fd()) {

0 commit comments

Comments
 (0)