Repositorio del curso CCOM4030 el semestre B91 del proyecto Artesanías con el Instituto de Cultura

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  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.rl.line += state.value;
  74. this.rl.cursor += state.value.length;
  75. this.render(state.isValid);
  76. }
  77. /**
  78. * When user press a key
  79. */
  80. onKeypress() {
  81. // If user press a key, just clear the default value
  82. if (this.opt.default) {
  83. this.opt.default = undefined;
  84. }
  85. this.render();
  86. }
  87. }
  88. module.exports = InputPrompt;