input.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. /**
  2. * `input` type prompt
  3. */
  4. var util = require('util');
  5. var chalk = require('chalk');
  6. var Base = require('./base');
  7. var observe = require('../utils/events');
  8. /**
  9. * Module exports
  10. */
  11. module.exports = Prompt;
  12. /**
  13. * Constructor
  14. */
  15. function Prompt() {
  16. return Base.apply(this, arguments);
  17. }
  18. util.inherits(Prompt, Base);
  19. /**
  20. * Start the Inquiry session
  21. * @param {Function} cb Callback when prompt is done
  22. * @return {this}
  23. */
  24. Prompt.prototype._run = function (cb) {
  25. this.done = cb;
  26. // Once user confirm (enter key)
  27. var events = observe(this.rl);
  28. var submit = events.line.map(this.filterInput.bind(this));
  29. var validation = this.handleSubmitEvents(submit);
  30. validation.success.forEach(this.onEnd.bind(this));
  31. validation.error.forEach(this.onError.bind(this));
  32. events.keypress.takeUntil(validation.success).forEach(this.onKeypress.bind(this));
  33. // Init
  34. this.render();
  35. return this;
  36. };
  37. /**
  38. * Render the prompt to screen
  39. * @return {Prompt} self
  40. */
  41. Prompt.prototype.render = function (error) {
  42. var bottomContent = '';
  43. var message = this.getQuestion();
  44. if (this.status === 'answered') {
  45. message += chalk.cyan(this.answer);
  46. } else {
  47. message += this.rl.line;
  48. }
  49. if (error) {
  50. bottomContent = chalk.red('>> ') + error;
  51. }
  52. this.screen.render(message, bottomContent);
  53. };
  54. /**
  55. * When user press `enter` key
  56. */
  57. Prompt.prototype.filterInput = function (input) {
  58. if (!input) {
  59. return this.opt.default == null ? '' : this.opt.default;
  60. }
  61. return input;
  62. };
  63. Prompt.prototype.onEnd = function (state) {
  64. this.answer = state.value;
  65. this.status = 'answered';
  66. // Re-render prompt
  67. this.render();
  68. this.screen.done();
  69. this.done(state.value);
  70. };
  71. Prompt.prototype.onError = function (state) {
  72. this.render(state.isValid);
  73. };
  74. /**
  75. * When user press a key
  76. */
  77. Prompt.prototype.onKeypress = function () {
  78. this.render();
  79. };