confirm.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. 'use strict';
  2. /**
  3. * `confirm` type prompt
  4. */
  5. var _ = {
  6. extend: require('lodash/extend'),
  7. isBoolean: require('lodash/isBoolean'),
  8. };
  9. var chalk = require('chalk');
  10. var { take, takeUntil } = require('rxjs/operators');
  11. var Base = require('./base');
  12. var observe = require('../utils/events');
  13. class ConfirmPrompt extends Base {
  14. constructor(questions, rl, answers) {
  15. super(questions, rl, answers);
  16. var rawDefault = true;
  17. _.extend(this.opt, {
  18. filter: function (input) {
  19. var value = rawDefault;
  20. if (input != null && input !== '') {
  21. value = /^y(es)?/i.test(input);
  22. }
  23. return value;
  24. },
  25. });
  26. if (_.isBoolean(this.opt.default)) {
  27. rawDefault = this.opt.default;
  28. }
  29. this.opt.default = rawDefault ? 'Y/n' : 'y/N';
  30. }
  31. /**
  32. * Start the Inquiry session
  33. * @param {Function} cb Callback when prompt is done
  34. * @return {this}
  35. */
  36. _run(cb) {
  37. this.done = cb;
  38. // Once user confirm (enter key)
  39. var events = observe(this.rl);
  40. events.keypress.pipe(takeUntil(events.line)).forEach(this.onKeypress.bind(this));
  41. events.line.pipe(take(1)).forEach(this.onEnd.bind(this));
  42. // Init
  43. this.render();
  44. return this;
  45. }
  46. /**
  47. * Render the prompt to screen
  48. * @return {ConfirmPrompt} self
  49. */
  50. render(answer) {
  51. var message = this.getQuestion();
  52. if (typeof answer === 'boolean') {
  53. message += chalk.cyan(answer ? 'Yes' : 'No');
  54. } else {
  55. message += this.rl.line;
  56. }
  57. this.screen.render(message);
  58. return this;
  59. }
  60. /**
  61. * When user press `enter` key
  62. */
  63. onEnd(input) {
  64. this.status = 'answered';
  65. var output = this.opt.filter(input);
  66. this.render(output);
  67. this.screen.done();
  68. this.done(output);
  69. }
  70. /**
  71. * When user press a key
  72. */
  73. onKeypress() {
  74. this.render();
  75. }
  76. }
  77. module.exports = ConfirmPrompt;