confirm.js 1.9 KB

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