prompt.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. 'use strict';
  2. const readline = require('readline');
  3. var _require = require('../util');
  4. const action = _require.action;
  5. const EventEmitter = require('events');
  6. var _require2 = require('sisteransi');
  7. const beep = _require2.beep,
  8. cursor = _require2.cursor;
  9. /**
  10. * Base prompt skeleton
  11. */
  12. class Prompt extends EventEmitter {
  13. constructor(opts = {}) {
  14. super();
  15. this.in = opts.in || process.stdin;
  16. this.out = opts.out || process.stdout;
  17. const rl = readline.createInterface(this.in);
  18. readline.emitKeypressEvents(this.in, rl);
  19. if (this.in.isTTY) this.in.setRawMode(true);
  20. const keypress = (str, key) => {
  21. let a = action(key);
  22. if (a === false) {
  23. this._ && this._(str, key);
  24. } else if (typeof this[a] === 'function') {
  25. this[a](key);
  26. } else {
  27. this.bell();
  28. }
  29. };
  30. const close = () => {
  31. this.out.write(cursor.show);
  32. this.in.removeListener('keypress', keypress);
  33. if (this.in.isTTY) this.in.setRawMode(false);
  34. rl.close();
  35. this.emit(this.aborted ? 'abort' : 'submit', this.value);
  36. };
  37. this.close = close;
  38. this.in.on('keypress', keypress);
  39. }
  40. fire() {
  41. this.emit('state', {
  42. value: this.value,
  43. aborted: !!this.aborted
  44. });
  45. }
  46. bell() {
  47. this.out.write(beep);
  48. }
  49. }
  50. module.exports = Prompt;