index.js 2.1 KB

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