tiny-spinner
Version:
A simple, yet beautiful, CLI spinner.
54 lines (53 loc) • 1.74 kB
JavaScript
/* IMPORT */
import Blocker from 'stdin-blocker';
import colors from 'tiny-colors';
import Cursor from 'tiny-cursor';
import { FRAMES, FRAMES_INTERVAL, SYMBOL_ERROR, SYMBOL_SUCCESS, SYMBOL_WARNING } from './constants.js';
import { isTTY, writeLine } from './utils.js';
/* MAIN */
class Spinner {
constructor() {
/* VARIABLES */
this.iteration = 0;
this.message = '';
/* API */
this.render = () => {
if (!isTTY())
return;
const frame = FRAMES[(this.iteration++) % FRAMES.length];
const line = `${colors.cyan(frame)} ${this.message}`;
writeLine(line);
};
this.start = (message) => {
if (this.intervalId)
return;
this.message = message;
Blocker.block();
Cursor.hide();
this.intervalId = setInterval(this.render, FRAMES_INTERVAL);
};
this.update = (message) => {
this.message = message;
};
this.warning = (message) => {
return this.stop(`${colors.yellow.bold(SYMBOL_WARNING)} ${message}`);
};
this.success = (message) => {
return this.stop(`${colors.green(SYMBOL_SUCCESS)} ${message}`);
};
this.error = (message) => {
return this.stop(`${colors.red(SYMBOL_ERROR)} ${message}`);
};
this.stop = (message = '') => {
if (!this.intervalId)
return;
Blocker.unblock();
Cursor.show();
clearInterval(this.intervalId);
const line = message ? `${message}\n` : '';
writeLine(line);
};
}
}
/* EXPORT */
export default Spinner;