confirm.js 1.7 KB

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