UNPKG

2.14 kBJavaScriptView Raw
1/*
2 * Copyright 2018 Adobe. All rights reserved.
3 * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License. You may obtain a copy
5 * of the License at http://www.apache.org/licenses/LICENSE-2.0
6 *
7 * Unless required by applicable law or agreed to in writing, software distributed under
8 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9 * OF ANY KIND, either express or implied. See the License for the specific language
10 * governing permissions and limitations under the License.
11 */
12
13const chalk = require('chalk');
14
15const spinnerFrames = process.platform === 'win32'
16 ? ['-', '\\', '|', '/']
17 : ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
18
19const createSpinner = (msg) => {
20 const hideCursor = () => {
21 this.running = false;
22 // ensure we quit after ctrl+c and show cursor again
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
71async function prompt(rl, question) {
72 return new Promise((resolve) => {
73 rl.question(question, resolve);
74 });
75}
76
77module.exports = {
78 createSpinner,
79 prompt,
80};