-
Notifications
You must be signed in to change notification settings - Fork 4
/
spinix.go
500 lines (438 loc) · 15.5 KB
/
spinix.go
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
// Package spinix provides terminal-based loading animations including spinners and progress bars.
// It supports customizable themes, colors, and speeds, allowing developers to use various styles
// to suit different terminal environments and aesthetics.
package spinix
import (
"fmt"
"strings"
"sync"
"time"
)
// ANSI escape codes
const (
clearScreen = "\033[2J"
clearLine = "\r\033[K"
moveCursor = "\033[H"
hideCursor = "\033[?25l"
showCursor = "\033[?25h"
)
const (
SpinnerClassicDots SpinnerStyle = "classic_dots"
SpinnerLineTheme SpinnerStyle = "line"
SpinnerPulsatingDot SpinnerStyle = "pulsating_dot"
SpinnerGrowingBlock SpinnerStyle = "growing_block"
SpinnerRotatingArrow SpinnerStyle = "rotating_arrow"
SpinnerArcLoader SpinnerStyle = "arc_loader"
SpinnerClock SpinnerStyle = "clock"
SpinnerCircleDots SpinnerStyle = "circle_dots"
SpinnerBouncingBall SpinnerStyle = "bouncing_ball"
SpinnerFadingSquares SpinnerStyle = "fading_squares"
SpinnerDotsFading SpinnerStyle = "dots_fading"
SpinnerEarth SpinnerStyle = "earth"
SpinnerSnake SpinnerStyle = "snake"
SpinnerTriangle SpinnerStyle = "triangle"
SpinnerSpiral SpinnerStyle = "spiral"
SpinnerWave SpinnerStyle = "wave"
SpinnerWeather SpinnerStyle = "weather"
SpinnerRunningPerson SpinnerStyle = "running_person"
SpinnerRunningCat SpinnerStyle = "running_cat"
SpinnerRunningDog SpinnerStyle = "running_dog"
SpinnerCycling SpinnerStyle = "cycling"
SpinnerCarLoading SpinnerStyle = "car_loading"
SpinnerRocket SpinnerStyle = "rocket"
SpinnerOrbit SpinnerStyle = "orbit"
SpinnerTrain SpinnerStyle = "train"
SpinnerAirplane SpinnerStyle = "airplane"
SpinnerFireworks SpinnerStyle = "fireworks"
SpinnerPizzaDelivery SpinnerStyle = "pizza_delivery"
SpinnerHeartbeat SpinnerStyle = "heartbeat"
)
const (
PbStyleBasic progressBarStyle = "basic"
PbStyleClassic progressBarStyle = "classic"
PbStyleMinimal progressBarStyle = "minimal"
PbStyleBold progressBarStyle = "bold"
PbStyleDashed progressBarStyle = "dashed"
PbStyleElegant progressBarStyle = "elegant"
PbStyleEmoji progressBarStyle = "emoji"
PbStyleFuturistic progressBarStyle = "futuristic"
PbStyleGreenDevelopment progressBarStyle = "green"
)
// ProgressBar represents a customizable terminal progress bar.
type ProgressBar struct {
width int // Width of the progress bar
progress int // Current progress percentage (0-100)
barChar string // Character to display for filled progress
emptyChar string // Character to display for empty progress
leftBorder string // Left border of the progress bar
rightBorder string // Right border of the progress bar
color string // Color for progress bar
label string // Optional label text
showLabel bool // Flag to show or hide label
showPercentage bool // Flag to show or hide progress percentage
speed time.Duration // Progress bar update speed
active bool // Indicates if the progress bar is active
mutex sync.Mutex // For thread safety
stopCh chan interface{} // Channel to signal stopping of the progress bar
callback func() // Optional callback to run after progress bar stops
}
// progressBarStyle represents the various style configurations for the progress bar.
type progressBarStyle string
type Spinner struct {
theme []string // Spinner animation frames
spinnerColor string // Color for loader
speed time.Duration // Interval to update the loader
message string // Message to show next to loader
messageColor string // Color for message text
showMessage bool // Indicate to show message or not
active bool // Status for loading indicator
mutex sync.Mutex // For thread-safe operations
stopCh chan struct{} // Channel to send stop signal
callback func() // Optional callback to run after spinner stops
lastFrame string // Optional frame to show after spinner stops
lastFrameColor string // Color for stop frame
lastMessage string // Optional message to display after spinner stops
lastMessageColor string // Color for last message
}
// SpinnerThemes defines several spinner animation styles.
var SpinnerThemes = map[SpinnerStyle][]string{
SpinnerClassicDots: {"⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"},
SpinnerLineTheme: {"-", "\\", "|", "/"},
SpinnerPulsatingDot: {"⠁", "⠂", "⠄", "⠂"},
SpinnerGrowingBlock: {"▁", "▃", "▄", "▅", "▆", "▇", "█", "▇", "▆", "▅", "▄", "▃"},
SpinnerRotatingArrow: {"→", "↘", "↓", "↙", "←", "↖", "↑", "↗"},
SpinnerArcLoader: {"◜", "◠", "◝", "◞", "◡", "◟"},
SpinnerClock: {"🕛", "🕐", "🕑", "🕒", "🕓", "🕔", "🕕", "🕖", "🕗", "🕘", "🕙", "🕚"},
SpinnerCircleDots: {"◐", "◓", "◑", "◒"},
SpinnerBouncingBall: {"⠁", "⠂", "⠄", "⠂"},
SpinnerFadingSquares: {"▖", "▘", "▝", "▗"},
SpinnerDotsFading: {"⠁", "⠂", "⠄", "⠂", "⠁", "⠂", "⠄", "⠂"},
SpinnerEarth: {"🌍", "🌎", "🌏"},
SpinnerSnake: {"⠈", "⠐", "⠠", "⢀", "⡀", "⠄", "⠂", "⠁"},
SpinnerTriangle: {"◢", "◣", "◤", "◥"},
SpinnerSpiral: {"▖", "▘", "▝", "▗", "▘", "▝", "▖", "▗"},
SpinnerWave: {"▁", "▂", "▃", "▄", "▅", "▆", "▇", "█", "▇", "▆", "▅", "▄", "▃", "▂", "▁"},
SpinnerWeather: {"🌤️", "⛅", "🌥️", "☁️", "🌧️", "⛈️", "🌩️", "🌨️"},
SpinnerRunningPerson: {"🏃💨", "🏃💨💨", "🏃💨💨💨", "🏃♂️💨", "🏃♂️💨💨", "🏃♀️💨", "🏃♀️💨💨"},
SpinnerRunningCat: {"🐱💨", "🐈💨", "🐱💨💨", "🐈💨💨"},
SpinnerRunningDog: {"🐕💨", "🐶💨", "🐕🦺💨", "🐕💨💨"},
SpinnerCycling: {"🚴", "🚴♂️", "🚴♀️", "🚵", "🚵♂️", "🚵♀️"},
SpinnerCarLoading: {"🚗💨", "🚙💨", "🚓💨", "🚕💨", "🚐💨", "🚔💨"},
SpinnerRocket: {"🚀", "🚀💨", "🚀💨💨", "🚀💨💨💨", "🚀🌌", "🚀🌠"},
SpinnerOrbit: {"🌑", "🌒", "🌓", "🌔", "🌕", "🌖", "🌗", "🌘"},
SpinnerTrain: {"🚆", "🚄", "🚅", "🚇", "🚊", "🚉"},
SpinnerAirplane: {"✈️ ", "🛫", "🛬", "✈️💨", "✈️💨💨"},
SpinnerFireworks: {"🎆", "🎇", "🎆🎇", "🎇🎆"},
SpinnerPizzaDelivery: {"🍕💨", "🍔💨", "🌭💨", "🍟💨"},
SpinnerHeartbeat: {"💓", "💗", "💖", "💘", "💞", "💝", "💖"},
}
// NewSpinner initializes a new Spinner with default settings and theme.
func NewSpinner() *Spinner {
return &Spinner{
theme: SpinnerThemes[SpinnerClassicDots], // Default theme
speed: 100 * time.Millisecond,
active: false,
spinnerColor: "\033[32m", // Green color as default
showMessage: true,
stopCh: make(chan struct{}),
}
}
// SetCallback sets a callback function to be executed when the spinner stops.
func (s *Spinner) SetCallback(cb func()) *Spinner {
s.callback = cb
return s
}
// Start begins the spinner animation in a goroutine.
func (s *Spinner) Start() {
s.mutex.Lock()
defer s.mutex.Unlock()
if s.active {
return
}
s.active = true
fmt.Print(hideCursor) // Hide the cursor in terminal
go s.animate()
}
// Stop ends the spinner animation and clears the spinner line.
func (s *Spinner) Stop() {
s.mutex.Lock()
defer s.mutex.Unlock()
if !s.active {
return
}
close(s.stopCh)
s.stopCh = make(chan struct{})
s.active = false
fmt.Print(clearLine) // Clear line
fmt.Print(showCursor) // Show the cursor in terminal
if len(s.lastFrame) != 0 || len(s.lastMessage) != 0 {
fmt.Printf("\r%s%s\033[0m %s%s\u001B[0m\n", s.lastFrameColor, s.lastFrame, s.lastMessageColor, s.lastMessage)
}
// Execute callback if set
if s.callback != nil {
s.callback()
}
}
// SetMessageColor sets the color code for the spinner's message text.
func (s *Spinner) SetMessageColor(colorCode string) *Spinner {
s.messageColor = colorCode
return s
}
// SetSpinnerColor sets the color code for the spinner itself.
func (s *Spinner) SetSpinnerColor(colorCode string) *Spinner {
s.spinnerColor = colorCode
return s
}
// SetMessage sets a message to display next to the spinner.
func (s *Spinner) SetMessage(message string) *Spinner {
s.message = message
s.showMessage = true
return s
}
// SetTheme selects a predefined spinner theme.
func (s *Spinner) SetTheme(theme SpinnerStyle) *Spinner {
s.theme = SpinnerThemes[theme]
return s
}
// SetCustomTheme allows setting a custom sequence of spinner frames.
func (s *Spinner) SetCustomTheme(frames []string) *Spinner {
s.theme = frames
return s
}
// SetSpeed adjusts the rotation speed of the spinner's frames.
func (s *Spinner) SetSpeed(speed time.Duration) *Spinner {
s.speed = speed
return s
}
// SetLastFrame allows setting last frame to display after spinner stops.
func (s *Spinner) SetLastFrame(frame string) *Spinner {
s.lastFrame = frame
return s
}
// SetLastFrameColor allows setting color of last frame to display after spinner stops.
func (s *Spinner) SetLastFrameColor(colorCode string) *Spinner {
s.lastFrameColor = colorCode
return s
}
// SetLastMessage sets a message to display after the spinner stops.
func (s *Spinner) SetLastMessage(message string) *Spinner {
s.lastMessage = message
return s
}
// SetLastMessageColor sets color of last message.
func (s *Spinner) SetLastMessageColor(colorCode string) *Spinner {
s.lastMessageColor = colorCode
return s
}
// animate is an internal function that continuously updates the spinner display
// until it receives a stop signal.
func (s *Spinner) animate() {
frameIdx := 0
for {
select {
case <-s.stopCh:
return
default:
fmt.Printf("\r%s%s\033[0m %s%s\033[0m", s.spinnerColor, s.theme[frameIdx], s.messageColor, s.message)
time.Sleep(s.speed)
frameIdx = (frameIdx + 1) % len(s.theme)
}
}
}
// SpinnerStyle represents a specific spinner theme.
type SpinnerStyle string
// NewProgressBar initializes a new ProgressBar with default settings.
func NewProgressBar() *ProgressBar {
return &ProgressBar{
width: 40,
barChar: "█",
emptyChar: " ",
leftBorder: "[",
rightBorder: "]",
color: "\033[32m", // Green color
showPercentage: true,
stopCh: make(chan interface{}),
speed: 100 * time.Millisecond,
}
}
// SetCallback sets a callback function to be executed when the progress bar stops.
func (pb *ProgressBar) SetCallback(cb func()) *ProgressBar {
pb.callback = cb
return pb
}
// SetWidth sets the width of the progress bar.
func (pb *ProgressBar) SetWidth(width int) *ProgressBar {
pb.width = width
return pb
}
// SetLabel sets a label to display next to the progress bar.
func (pb *ProgressBar) SetLabel(label string) *ProgressBar {
pb.label = label
pb.showLabel = true
return pb
}
// SetShowPercentage toggles the display of the progress percentage.
func (pb *ProgressBar) SetShowPercentage(show bool) *ProgressBar {
pb.showPercentage = show
return pb
}
// SetBarChar sets the character to display as filled progress.
func (pb *ProgressBar) SetBarChar(char string) *ProgressBar {
pb.barChar = char
return pb
}
// SetEmptyChar sets the character to display as empty progress.
func (pb *ProgressBar) SetEmptyChar(char string) *ProgressBar {
pb.emptyChar = char
return pb
}
// SetBorders sets the characters for the left and right borders of the progress bar.
func (pb *ProgressBar) SetBorders(left, right string) *ProgressBar {
pb.leftBorder = left
pb.rightBorder = right
return pb
}
// SetSpeed sets the speed of the progress bar update interval.
func (pb *ProgressBar) SetSpeed(speed time.Duration) *ProgressBar {
pb.speed = speed
return pb
}
// SetColor sets the color for the progress bar.
func (pb *ProgressBar) SetColor(color string) *ProgressBar {
pb.color = color
return pb
}
// Start begins the progress bar animation in a separate goroutine.
func (pb *ProgressBar) Start() {
pb.mutex.Lock()
defer pb.mutex.Unlock()
if pb.active {
return
}
pb.active = true
fmt.Print(hideCursor)
go pb.animate()
}
// Stop ends the progress bar animation and clears the progress bar line.
func (pb *ProgressBar) Stop() {
pb.mutex.Lock()
defer pb.mutex.Unlock()
if !pb.active {
return
}
close(pb.stopCh)
pb.stopCh = make(chan interface{})
pb.active = false
fmt.Print(clearLine) // Clear line
fmt.Print(showCursor) // Hide the cursor in terminal
// Execute callback if set
if pb.callback != nil {
pb.callback()
}
}
// Update sets the current progress percentage.
func (pb *ProgressBar) Update(progress int) {
pb.mutex.Lock()
defer pb.mutex.Unlock()
if progress >= 0 && progress <= 100 {
pb.progress = progress
}
}
// animate is an internal function that continuously updates the progress bar display.
func (pb *ProgressBar) animate() {
for {
select {
case <-pb.stopCh:
return
default:
pb.render()
time.Sleep(pb.speed)
}
}
}
// render generates the progress bar output based on current progress.
func (pb *ProgressBar) render() {
pb.mutex.Lock()
defer pb.mutex.Unlock()
fillWidth := int(float64(pb.width) * float64(pb.progress) / 100)
emptyWidth := pb.width - fillWidth
bar := fmt.Sprintf("\r%s%s%s%s%s\033[0m", pb.color, pb.leftBorder,
strings.Repeat(pb.barChar, fillWidth),
strings.Repeat(pb.emptyChar, emptyWidth), pb.rightBorder)
if pb.showPercentage {
bar += fmt.Sprintf(" %3d%%", pb.progress)
}
if pb.showLabel {
bar += fmt.Sprintf(" %s", pb.label)
}
fmt.Print(bar)
}
// SetStyle configures the progress bar style based on predefined styles.
func (pb *ProgressBar) SetStyle(style progressBarStyle) *ProgressBar {
switch style {
case PbStyleBasic:
pb.width = 40
pb.barChar = "="
pb.emptyChar = "-"
pb.leftBorder = "|"
pb.rightBorder = "|"
pb.color = "\033[34m" // Blue
case PbStyleClassic:
pb.width = 30
pb.barChar = "#"
pb.emptyChar = "."
pb.leftBorder = "["
pb.rightBorder = "]"
pb.color = "\033[32m" // Green
case PbStyleMinimal:
pb.width = 20
pb.barChar = "*"
pb.emptyChar = " "
pb.leftBorder = ""
pb.rightBorder = ""
pb.color = "\033[36m" // Cyan
case PbStyleBold:
pb.width = 50
pb.barChar = "■"
pb.emptyChar = " "
pb.leftBorder = "❮"
pb.rightBorder = "❯"
pb.color = "\033[35m" // Purple
case PbStyleDashed:
pb.width = 45
pb.barChar = "▮"
pb.emptyChar = "▯"
pb.leftBorder = "["
pb.rightBorder = "]"
pb.color = "\033[31m" // Red
case PbStyleElegant:
pb.width = 35
pb.barChar = "▰"
pb.emptyChar = "▱"
pb.leftBorder = "❬"
pb.rightBorder = "❭"
pb.color = "\033[94m" // Light Blue
case PbStyleEmoji:
pb.width = 25
pb.barChar = "🚀"
pb.emptyChar = "✨"
pb.leftBorder = "🚩"
pb.rightBorder = "🎯"
pb.color = "\033[33m" // Yellow
case PbStyleFuturistic:
pb.width = 40
pb.barChar = "◉"
pb.emptyChar = "○"
pb.leftBorder = "⟦"
pb.rightBorder = "⟧"
pb.color = "\033[96m" // Cyan
case PbStyleGreenDevelopment:
pb.width = 25
pb.barChar = "🌿"
pb.emptyChar = "__"
pb.leftBorder = "🌱"
pb.rightBorder = "🌳"
pb.color = "\033[92m" // Green
}
return pb
}