| 1 | 'use strict';
|
|---|
| 2 |
|
|---|
| 3 | const readline = require('readline');
|
|---|
| 4 | const { action } = require('../util');
|
|---|
| 5 | const EventEmitter = require('events');
|
|---|
| 6 | const { beep, cursor } = require('sisteransi');
|
|---|
| 7 | const color = require('kleur');
|
|---|
| 8 |
|
|---|
| 9 | /**
|
|---|
| 10 | * Base prompt skeleton
|
|---|
| 11 | * @param {Stream} [opts.stdin] The Readable stream to listen to
|
|---|
| 12 | * @param {Stream} [opts.stdout] The Writable stream to write readline data to
|
|---|
| 13 | */
|
|---|
| 14 | class Prompt extends EventEmitter {
|
|---|
| 15 | constructor(opts={}) {
|
|---|
| 16 | super();
|
|---|
| 17 |
|
|---|
| 18 | this.firstRender = true;
|
|---|
| 19 | this.in = opts.stdin || process.stdin;
|
|---|
| 20 | this.out = opts.stdout || process.stdout;
|
|---|
| 21 | this.onRender = (opts.onRender || (() => void 0)).bind(this);
|
|---|
| 22 | const rl = readline.createInterface({ input:this.in, escapeCodeTimeout:50 });
|
|---|
| 23 | readline.emitKeypressEvents(this.in, rl);
|
|---|
| 24 |
|
|---|
| 25 | if (this.in.isTTY) this.in.setRawMode(true);
|
|---|
| 26 | const isSelect = [ 'SelectPrompt', 'MultiselectPrompt' ].indexOf(this.constructor.name) > -1;
|
|---|
| 27 | const keypress = (str, key) => {
|
|---|
| 28 | let a = action(key, isSelect);
|
|---|
| 29 | if (a === false) {
|
|---|
| 30 | this._ && this._(str, key);
|
|---|
| 31 | } else if (typeof this[a] === 'function') {
|
|---|
| 32 | this[a](key);
|
|---|
| 33 | } else {
|
|---|
| 34 | this.bell();
|
|---|
| 35 | }
|
|---|
| 36 | };
|
|---|
| 37 |
|
|---|
| 38 | this.close = () => {
|
|---|
| 39 | this.out.write(cursor.show);
|
|---|
| 40 | this.in.removeListener('keypress', keypress);
|
|---|
| 41 | if (this.in.isTTY) this.in.setRawMode(false);
|
|---|
| 42 | rl.close();
|
|---|
| 43 | this.emit(this.aborted ? 'abort' : this.exited ? 'exit' : 'submit', this.value);
|
|---|
| 44 | this.closed = true;
|
|---|
| 45 | };
|
|---|
| 46 |
|
|---|
| 47 | this.in.on('keypress', keypress);
|
|---|
| 48 | }
|
|---|
| 49 |
|
|---|
| 50 | fire() {
|
|---|
| 51 | this.emit('state', {
|
|---|
| 52 | value: this.value,
|
|---|
| 53 | aborted: !!this.aborted,
|
|---|
| 54 | exited: !!this.exited
|
|---|
| 55 | });
|
|---|
| 56 | }
|
|---|
| 57 |
|
|---|
| 58 | bell() {
|
|---|
| 59 | this.out.write(beep);
|
|---|
| 60 | }
|
|---|
| 61 |
|
|---|
| 62 | render() {
|
|---|
| 63 | this.onRender(color);
|
|---|
| 64 | if (this.firstRender) this.firstRender = false;
|
|---|
| 65 | }
|
|---|
| 66 | }
|
|---|
| 67 |
|
|---|
| 68 | module.exports = Prompt;
|
|---|