input.js 1.8 KB

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