index.js 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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. const stripAnsi = require('strip-ansi');
  7. const wcwidth = require('wcwidth');
  8. const isInteractive = require('is-interactive');
  9. const TEXT = Symbol('text');
  10. const PREFIX_TEXT = Symbol('prefixText');
  11. const noop = () => {};
  12. const ASCII_ETX_CODE = 0x03; // Ctrl+C emits this code
  13. class Ora {
  14. constructor(options) {
  15. if (typeof options === 'string') {
  16. options = {
  17. text: options
  18. };
  19. }
  20. this.options = {
  21. text: '',
  22. color: 'cyan',
  23. stream: process.stderr,
  24. discardStdin: true,
  25. ...options
  26. };
  27. this.spinner = this.options.spinner;
  28. this.color = this.options.color;
  29. this.hideCursor = this.options.hideCursor !== false;
  30. this.interval = this.options.interval || this.spinner.interval || 100;
  31. this.stream = this.options.stream;
  32. this.id = undefined;
  33. this.isEnabled = typeof this.options.isEnabled === 'boolean' ? this.options.isEnabled : isInteractive({stream: this.stream});
  34. // Set *after* `this.stream`
  35. this.text = this.options.text;
  36. this.prefixText = this.options.prefixText;
  37. this.linesToClear = 0;
  38. this.indent = this.options.indent;
  39. this.discardStdin = this.options.discardStdin;
  40. }
  41. get indent() {
  42. return this._indent;
  43. }
  44. set indent(indent = 0) {
  45. if (!(indent >= 0 && Number.isInteger(indent))) {
  46. throw new Error('The `indent` option must be an integer from 0 and up');
  47. }
  48. this._indent = indent;
  49. }
  50. _updateInterval(interval) {
  51. if (interval !== undefined) {
  52. this.interval = interval;
  53. }
  54. }
  55. get spinner() {
  56. return this._spinner;
  57. }
  58. set spinner(spinner) {
  59. this.frameIndex = 0;
  60. if (typeof spinner === 'object') {
  61. if (spinner.frames === undefined) {
  62. throw new Error('The given spinner must have a `frames` property');
  63. }
  64. this._spinner = spinner;
  65. } else if (process.platform === 'win32') {
  66. this._spinner = cliSpinners.line;
  67. } else if (spinner === undefined) {
  68. // Set default spinner
  69. this._spinner = cliSpinners.dots;
  70. } else if (cliSpinners[spinner]) {
  71. this._spinner = cliSpinners[spinner];
  72. } else {
  73. throw new Error(`There is no built-in spinner named '${spinner}'. See https://github.com/sindresorhus/cli-spinners/blob/master/spinners.json for a full list.`);
  74. }
  75. this._updateInterval(this._spinner.interval);
  76. }
  77. get text() {
  78. return this[TEXT];
  79. }
  80. get prefixText() {
  81. return this[PREFIX_TEXT];
  82. }
  83. get isSpinning() {
  84. return this.id !== undefined;
  85. }
  86. updateLineCount() {
  87. const columns = this.stream.columns || 80;
  88. const fullPrefixText = (typeof this[PREFIX_TEXT] === 'string') ? this[PREFIX_TEXT] + '-' : '';
  89. this.lineCount = stripAnsi(fullPrefixText + '--' + this[TEXT]).split('\n').reduce((count, line) => {
  90. return count + Math.max(1, Math.ceil(wcwidth(line) / columns));
  91. }, 0);
  92. }
  93. set text(value) {
  94. this[TEXT] = value;
  95. this.updateLineCount();
  96. }
  97. set prefixText(value) {
  98. this[PREFIX_TEXT] = value;
  99. this.updateLineCount();
  100. }
  101. frame() {
  102. const {frames} = this.spinner;
  103. let frame = frames[this.frameIndex];
  104. if (this.color) {
  105. frame = chalk[this.color](frame);
  106. }
  107. this.frameIndex = ++this.frameIndex % frames.length;
  108. const fullPrefixText = (typeof this.prefixText === 'string' && this.prefixText !== '') ? this.prefixText + ' ' : '';
  109. const fullText = typeof this.text === 'string' ? ' ' + this.text : '';
  110. return fullPrefixText + frame + fullText;
  111. }
  112. clear() {
  113. if (!this.isEnabled || !this.stream.isTTY) {
  114. return this;
  115. }
  116. for (let i = 0; i < this.linesToClear; i++) {
  117. if (i > 0) {
  118. this.stream.moveCursor(0, -1);
  119. }
  120. this.stream.clearLine();
  121. this.stream.cursorTo(this.indent);
  122. }
  123. this.linesToClear = 0;
  124. return this;
  125. }
  126. render() {
  127. this.clear();
  128. this.stream.write(this.frame());
  129. this.linesToClear = this.lineCount;
  130. return this;
  131. }
  132. start(text) {
  133. if (text) {
  134. this.text = text;
  135. }
  136. if (!this.isEnabled) {
  137. this.stream.write(`- ${this.text}\n`);
  138. return this;
  139. }
  140. if (this.isSpinning) {
  141. return this;
  142. }
  143. if (this.hideCursor) {
  144. cliCursor.hide(this.stream);
  145. }
  146. if (this.discardStdin && process.stdin.isTTY) {
  147. this.startDiscardingStdin();
  148. }
  149. this.render();
  150. this.id = setInterval(this.render.bind(this), this.interval);
  151. return this;
  152. }
  153. stop() {
  154. if (!this.isEnabled) {
  155. return this;
  156. }
  157. clearInterval(this.id);
  158. this.id = undefined;
  159. this.frameIndex = 0;
  160. this.clear();
  161. if (this.hideCursor) {
  162. cliCursor.show(this.stream);
  163. }
  164. if (this.discardStdin && process.stdin.isTTY) {
  165. this.stopDiscardingStdin();
  166. }
  167. return this;
  168. }
  169. startDiscardingStdin() {
  170. const {stdin} = process;
  171. this._stdinOldRawMode = stdin.isRaw;
  172. this._stdinOldEmit = stdin.emit;
  173. this._stdinOldEmitOwnProperty = Object.prototype.hasOwnProperty.call(stdin, 'emit');
  174. stdin.setRawMode(true);
  175. stdin.on('data', noop);
  176. stdin.resume();
  177. const self = this;
  178. stdin.emit = function (event, data, ...args) {
  179. if (event === 'keypress') { // Fixes readline behavior
  180. return;
  181. }
  182. if (event === 'data' && data.includes(ASCII_ETX_CODE)) {
  183. process.emit('SIGINT');
  184. }
  185. self._stdinOldEmit.apply(this, [event, data, ...args]);
  186. };
  187. }
  188. stopDiscardingStdin() {
  189. if (this._stdinOldEmit !== undefined) {
  190. const {stdin} = process;
  191. stdin.setRawMode(this._stdinOldRawMode);
  192. stdin.removeListener('data', noop);
  193. if (stdin.listenerCount('data') === 0) {
  194. stdin.pause();
  195. }
  196. if (this._stdinOldEmitOwnProperty) {
  197. stdin.emit = this._stdinOldEmit;
  198. } else {
  199. delete stdin.emit;
  200. }
  201. this._stdinOldRawMode = undefined;
  202. this._stdinOldEmit = undefined;
  203. this._stdinOldEmitOwnProperty = undefined;
  204. }
  205. }
  206. succeed(text) {
  207. return this.stopAndPersist({symbol: logSymbols.success, text});
  208. }
  209. fail(text) {
  210. return this.stopAndPersist({symbol: logSymbols.error, text});
  211. }
  212. warn(text) {
  213. return this.stopAndPersist({symbol: logSymbols.warning, text});
  214. }
  215. info(text) {
  216. return this.stopAndPersist({symbol: logSymbols.info, text});
  217. }
  218. stopAndPersist(options = {}) {
  219. const prefixText = options.prefixText || this.prefixText;
  220. const fullPrefixText = (typeof prefixText === 'string' && prefixText !== '') ? prefixText + ' ' : '';
  221. const text = options.text || this.text;
  222. const fullText = (typeof text === 'string') ? ' ' + text : '';
  223. this.stop();
  224. this.stream.write(`${fullPrefixText}${options.symbol || ' '}${fullText}\n`);
  225. return this;
  226. }
  227. }
  228. const oraFactory = function (options) {
  229. return new Ora(options);
  230. };
  231. module.exports = oraFactory;
  232. module.exports.promise = (action, options) => {
  233. // eslint-disable-next-line promise/prefer-await-to-then
  234. if (typeof action.then !== 'function') {
  235. throw new TypeError('Parameter `action` must be a Promise');
  236. }
  237. const spinner = new Ora(options);
  238. spinner.start();
  239. (async () => {
  240. try {
  241. await action;
  242. spinner.succeed();
  243. } catch (_) {
  244. spinner.fail();
  245. }
  246. })();
  247. return spinner;
  248. };