confirm.js 1.7 KB

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