UNPKG

1.87 kBJavaScriptView Raw
1'use strict';
2var chalk = require('chalk');
3var cliCursor = require('cli-cursor');
4var cliSpinners = require('cli-spinners');
5var objectAssign = require('object-assign');
6
7function Ora(options) {
8 if (!(this instanceof Ora)) {
9 return new Ora(options);
10 }
11
12 if (typeof options === 'string') {
13 options = {
14 text: options
15 };
16 }
17
18 this.options = objectAssign({
19 text: '',
20 color: 'cyan',
21 stream: process.stderr
22 }, options);
23
24 var sp = this.options.spinner;
25 this.spinner = typeof sp === 'object' ? sp : (process.platform === 'win32' ? cliSpinners.line : (cliSpinners[sp] || cliSpinners.dots)); // eslint-disable-line
26
27 if (this.spinner.frames === undefined) {
28 throw new Error('Spinner must define `frames`');
29 }
30
31 this.text = this.options.text;
32 this.color = this.options.color;
33 this.interval = this.options.interval || this.spinner.interval || 100;
34 this.stream = this.options.stream;
35 this.id = null;
36 this.frameIndex = 0;
37 this.enabled = (this.stream && this.stream.isTTY) && !process.env.CI;
38}
39
40Ora.prototype.frame = function () {
41 var frames = this.spinner.frames;
42 var frame = frames[this.frameIndex];
43
44 if (this.color) {
45 frame = chalk[this.color](frame);
46 }
47
48 this.frameIndex = ++this.frameIndex % frames.length;
49
50 return frame + ' ' + this.text;
51};
52
53Ora.prototype.clear = function () {
54 if (!this.enabled) {
55 return;
56 }
57
58 this.stream.clearLine();
59 this.stream.cursorTo(0);
60};
61
62Ora.prototype.render = function () {
63 this.clear();
64 this.stream.write(this.frame());
65};
66
67Ora.prototype.start = function () {
68 if (!this.enabled || this.id) {
69 return;
70 }
71
72 cliCursor.hide();
73 this.render();
74 this.id = setInterval(this.render.bind(this), this.interval);
75};
76
77Ora.prototype.stop = function () {
78 if (!this.enabled) {
79 return;
80 }
81
82 clearInterval(this.id);
83 this.id = null;
84 this.frameIndex = 0;
85 this.clear();
86 cliCursor.show();
87};
88
89module.exports = Ora;