1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 | const chalk = require('chalk');
|
14 |
|
15 | const spinnerFrames = process.platform === 'win32'
|
16 | ? ['-', '\\', '|', '/']
|
17 | : ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
|
18 |
|
19 | const createSpinner = (msg) => {
|
20 | const hideCursor = () => {
|
21 | this.running = false;
|
22 |
|
23 | process.stdout.write('\u001b[?25h');
|
24 | process.exit(0);
|
25 | };
|
26 | process.once('SIGINT', hideCursor);
|
27 |
|
28 | return {
|
29 | i: 0,
|
30 | running: false,
|
31 | s: process.stdout,
|
32 | written: false,
|
33 |
|
34 | run() {
|
35 | if (this.running) {
|
36 | if (msg) {
|
37 | this.s.write(`${chalk.cyan(spinnerFrames[this.i])} ${msg}`);
|
38 | this.s.cursorTo(0);
|
39 | } else {
|
40 | this.s.write(chalk.cyan(spinnerFrames[this.i]));
|
41 | this.s.moveCursor(-1);
|
42 | }
|
43 | this.written = true;
|
44 | this.i = (this.i + 1) % spinnerFrames.length;
|
45 | setTimeout(this.run.bind(this), 100);
|
46 | }
|
47 | },
|
48 |
|
49 | start() {
|
50 | if (!this.s.moveCursor) {
|
51 | return this;
|
52 | }
|
53 | this.s.write('\u001b[?25l');
|
54 | this.running = true;
|
55 | this.run();
|
56 | return this;
|
57 | },
|
58 |
|
59 | stop() {
|
60 | this.s.write('\u001b[?25h');
|
61 | this.running = false;
|
62 | if (this.written) {
|
63 | this.s.clearLine(1);
|
64 | }
|
65 | process.removeListener('SIGINT', hideCursor);
|
66 | return this;
|
67 | },
|
68 | };
|
69 | };
|
70 |
|
71 | async function prompt(rl, question) {
|
72 | return new Promise((resolve) => {
|
73 | rl.question(question, resolve);
|
74 | });
|
75 | }
|
76 |
|
77 | module.exports = {
|
78 | createSpinner,
|
79 | prompt,
|
80 | };
|