Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

input.js 2.2KB

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