UNPKG

3.21 kBJavaScriptView Raw
1/*
2 |--------------------------------------------------------------------------
3 | Modification version of cli-spinner package.
4 | Need to add padding before displaying spinner
5 |--------------------------------------------------------------------------
6 */
7
8var readline = require('readline');
9var clc = require('cli-color');
10
11var defaultSpinnerString = 0;
12var defaultSpinnerDelay = 60;
13
14var Spinner = function(textToShow, prefix){
15 this.prefix = prefix || '';
16 this.text = textToShow || '';
17 this.setSpinnerString(defaultSpinnerString);
18 this.setSpinnerDelay(defaultSpinnerDelay);
19};
20
21Spinner.spinners = [
22 '|/-\\',
23 '⠂-–—–-',
24 '◐◓◑◒',
25 '◴◷◶◵',
26 '◰◳◲◱',
27 '▖▘▝▗',
28 '■□▪▫',
29 '▌▀▐▄',
30 '▉▊▋▌▍▎▏▎▍▌▋▊▉',
31 '▁▃▄▅▆▇█▇▆▅▄▃',
32 '←↖↑↗→↘↓↙',
33 '┤┘┴└├┌┬┐',
34 '◢◣◤◥',
35 '.oO°Oo.',
36 '.oO@*',
37 '🌍🌎🌏',
38 '◡◡ ⊙⊙ ◠◠',
39 '☱☲☴',
40 '⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏',
41 '⠋⠙⠚⠞⠖⠦⠴⠲⠳⠓',
42 '⠄⠆⠇⠋⠙⠸⠰⠠⠰⠸⠙⠋⠇⠆',
43 '⠋⠙⠚⠒⠂⠂⠒⠲⠴⠦⠖⠒⠐⠐⠒⠓⠋',
44 '⠁⠉⠙⠚⠒⠂⠂⠒⠲⠴⠤⠄⠄⠤⠴⠲⠒⠂⠂⠒⠚⠙⠉⠁',
45 '⠈⠉⠋⠓⠒⠐⠐⠒⠖⠦⠤⠠⠠⠤⠦⠖⠒⠐⠐⠒⠓⠋⠉⠈',
46 '⠁⠁⠉⠙⠚⠒⠂⠂⠒⠲⠴⠤⠄⠄⠤⠠⠠⠤⠦⠖⠒⠐⠐⠒⠓⠋⠉⠈⠈',
47 '⢄⢂⢁⡁⡈⡐⡠',
48 '⢹⢺⢼⣸⣇⡧⡗⡏',
49 '⣾⣽⣻⢿⡿⣟⣯⣷',
50 '⠁⠂⠄⡀⢀⠠⠐⠈',
51 '🌑🌒🌓🌔🌕🌝🌖🌗🌘🌚'
52];
53
54Spinner.setDefaultSpinnerString = function(value) {
55 defaultSpinnerString = value;
56};
57
58Spinner.setDefaultSpinnerDelay = function(value) {
59 defaultSpinnerDelay = value;
60};
61
62Spinner.prototype.start = function() {
63 var current = 0;
64 var self = this;
65 this.id = setInterval(function() {
66 var msg = self.text.indexOf('%s') > -1 ? self.text.replace('%s', self.chars[current]) : self.chars[current] + ' ' + self.text;
67 clearLine();
68 process.stdout.write(clc.blue(self.prefix + msg));
69 current = ++current % self.chars.length;
70 }, this.delay);
71};
72
73Spinner.prototype.isSpinning = function() {
74 return this.id !== undefined;
75};
76
77Spinner.prototype.setSpinnerDelay = function(n) {
78 this.delay = n;
79};
80
81Spinner.prototype.setSpinnerString = function(str) {
82 this.chars = mapToSpinner(str, this.spinners).split('');
83};
84
85Spinner.prototype.setSpinnerTitle = function(str) {
86 this.text = str;
87};
88
89Spinner.prototype.stop = function(clear) {
90 clearInterval(this.id);
91 this.id = undefined;
92 if (clear) {
93 clearLine();
94 }
95};
96
97// Helpers
98
99function isInt(value) {
100 return (typeof value==='number' && (value%1)===0);
101}
102
103function mapToSpinner(value, spinners) {
104 // Not an integer, return as strng
105 if (!isInt(value)) {
106 return value + '';
107 }
108
109 // Check if index is within bounds
110 value = (value >= Spinner.spinners.length) ? 0 : value;
111 // If negative, count from the end
112 value = (value < 0) ? Spinner.spinners.length + value : value;
113
114 return Spinner.spinners[value];
115}
116
117function clearLine() {
118 readline.clearLine(process.stdout, 0);
119 readline.cursorTo(process.stdout, 0);
120}
121
122exports.Spinner = Spinner;