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