index.js 1.9 KB

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