confirm.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. "use strict";
  2. const color = require('kleur');
  3. const Prompt = require('./prompt');
  4. const _require = require('../util'),
  5. style = _require.style,
  6. clear = _require.clear;
  7. const _require2 = require('sisteransi'),
  8. erase = _require2.erase,
  9. cursor = _require2.cursor;
  10. /**
  11. * ConfirmPrompt Base Element
  12. * @param {Object} opts Options
  13. * @param {String} opts.message Message
  14. * @param {Boolean} [opts.initial] Default value (true/false)
  15. * @param {Stream} [opts.stdin] The Readable stream to listen to
  16. * @param {Stream} [opts.stdout] The Writable stream to write readline data to
  17. * @param {String} [opts.yes] The "Yes" label
  18. * @param {String} [opts.yesOption] The "Yes" option when choosing between yes/no
  19. * @param {String} [opts.no] The "No" label
  20. * @param {String} [opts.noOption] The "No" option when choosing between yes/no
  21. */
  22. class ConfirmPrompt extends Prompt {
  23. constructor(opts = {}) {
  24. super(opts);
  25. this.msg = opts.message;
  26. this.value = opts.initial;
  27. this.initialValue = !!opts.initial;
  28. this.yesMsg = opts.yes || 'yes';
  29. this.yesOption = opts.yesOption || '(Y/n)';
  30. this.noMsg = opts.no || 'no';
  31. this.noOption = opts.noOption || '(y/N)';
  32. this.render();
  33. }
  34. reset() {
  35. this.value = this.initialValue;
  36. this.fire();
  37. this.render();
  38. }
  39. exit() {
  40. this.abort();
  41. }
  42. abort() {
  43. this.done = this.aborted = true;
  44. this.fire();
  45. this.render();
  46. this.out.write('\n');
  47. this.close();
  48. }
  49. submit() {
  50. this.value = this.value || false;
  51. this.done = true;
  52. this.aborted = false;
  53. this.fire();
  54. this.render();
  55. this.out.write('\n');
  56. this.close();
  57. }
  58. _(c, key) {
  59. if (c.toLowerCase() === 'y') {
  60. this.value = true;
  61. return this.submit();
  62. }
  63. if (c.toLowerCase() === 'n') {
  64. this.value = false;
  65. return this.submit();
  66. }
  67. return this.bell();
  68. }
  69. render() {
  70. if (this.closed) return;
  71. if (this.firstRender) this.out.write(cursor.hide);else this.out.write(clear(this.outputText, this.out.columns));
  72. super.render();
  73. this.outputText = [style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(this.done), this.done ? this.value ? this.yesMsg : this.noMsg : color.gray(this.initialValue ? this.yesOption : this.noOption)].join(' ');
  74. this.out.write(erase.line + cursor.to(0) + this.outputText);
  75. }
  76. }
  77. module.exports = ConfirmPrompt;