confirm.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. 'use strict';
  2. const color = require('kleur');
  3. const Prompt = require('./prompt');
  4. var _require = require('../util');
  5. const style = _require.style,
  6. clear = _require.clear;
  7. var _require2 = require('sisteransi');
  8. const 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. */
  16. class ConfirmPrompt extends Prompt {
  17. constructor(opts = {}) {
  18. super(opts);
  19. this.msg = opts.message;
  20. this.value = opts.initial;
  21. this.initialValue = !!opts.initial;
  22. this.render(true);
  23. }
  24. reset() {
  25. this.value = this.initialValue;
  26. this.fire();
  27. this.render();
  28. }
  29. abort() {
  30. this.done = this.aborted = true;
  31. this.fire();
  32. this.render();
  33. this.out.write('\n');
  34. this.close();
  35. }
  36. submit() {
  37. this.value = this.value || false;
  38. this.done = true;
  39. this.aborted = false;
  40. this.fire();
  41. this.render();
  42. this.out.write('\n');
  43. this.close();
  44. }
  45. _(c, key) {
  46. if (c.toLowerCase() === 'y') {
  47. this.value = true;
  48. return this.submit();
  49. }
  50. if (c.toLowerCase() === 'n') {
  51. this.value = false;
  52. return this.submit();
  53. }
  54. return this.bell();
  55. }
  56. render(first) {
  57. if (first) this.out.write(cursor.hide);
  58. this.out.write(erase.line + cursor.to(0) + [style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(this.done), this.done ? this.value ? 'yes' : 'no' : color.gray(this.initialValue ? '(Y/n)' : '(y/N)')].join(' '));
  59. }
  60. }
  61. module.exports = ConfirmPrompt;