confirm.js 1.8 KB

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