confirm.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. const color = require('kleur');
  2. const Prompt = require('./prompt');
  3. const { style, clear } = require('../util');
  4. const { erase, cursor } = require('sisteransi');
  5. /**
  6. * ConfirmPrompt Base Element
  7. * @param {Object} opts Options
  8. * @param {String} opts.message Message
  9. * @param {Boolean} [opts.initial] Default value (true/false)
  10. */
  11. class ConfirmPrompt extends Prompt {
  12. constructor(opts={}) {
  13. super(opts);
  14. this.msg = opts.message;
  15. this.value = opts.initial;
  16. this.initialValue = !!opts.initial;
  17. this.render(true);
  18. }
  19. reset() {
  20. this.value = this.initialValue;
  21. this.fire();
  22. this.render();
  23. }
  24. abort() {
  25. this.done = this.aborted = true;
  26. this.fire();
  27. this.render();
  28. this.out.write('\n');
  29. this.close();
  30. }
  31. submit() {
  32. this.value = this.value || false;
  33. this.done = true;
  34. this.aborted = false;
  35. this.fire();
  36. this.render();
  37. this.out.write('\n');
  38. this.close();
  39. }
  40. _(c, key) {
  41. if (c.toLowerCase() === 'y') {
  42. this.value = true;
  43. return this.submit();
  44. }
  45. if (c.toLowerCase() === 'n') {
  46. this.value = false;
  47. return this.submit();
  48. }
  49. return this.bell();
  50. }
  51. render(first) {
  52. if (first) this.out.write(cursor.hide);
  53. this.out.write(
  54. erase.line +
  55. cursor.to(0) +
  56. [
  57. style.symbol(this.done, this.aborted),
  58. color.bold(this.msg),
  59. style.delimiter(this.done),
  60. this.done
  61. ? this.value ? 'yes' : 'no'
  62. : color.gray(this.initialValue ? '(Y/n)' : '(y/N)')
  63. ].join(' ')
  64. );
  65. }
  66. }
  67. module.exports = ConfirmPrompt;