toggle.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. const color = require('kleur');
  2. const Prompt = require('./prompt');
  3. const { style, clear } = require('../util');
  4. const { cursor, erase } = require('sisteransi');
  5. /**
  6. * TogglePrompt Base Element
  7. * @param {Object} opts Options
  8. * @param {String} opts.message Message
  9. * @param {Boolean} [opts.initial=false] Default value
  10. * @param {String} [opts.active='no'] Active label
  11. * @param {String} [opts.inactive='off'] Inactive label
  12. */
  13. class TogglePrompt extends Prompt {
  14. constructor(opts={}) {
  15. super(opts);
  16. this.msg = opts.message;
  17. this.value = !!opts.initial;
  18. this.active = opts.active;
  19. this.inactive = opts.inactive;
  20. this.initialValue = this.value;
  21. this.render(true);
  22. }
  23. reset() {
  24. this.value = this.initialValue;
  25. this.fire();
  26. this.render();
  27. }
  28. abort() {
  29. this.done = this.aborted = true;
  30. this.fire();
  31. this.render();
  32. this.out.write('\n');
  33. this.close();
  34. }
  35. submit() {
  36. this.done = true;
  37. this.aborted = false;
  38. this.fire();
  39. this.render();
  40. this.out.write('\n');
  41. this.close();
  42. }
  43. deactivate() {
  44. if (this.value === false) return this.bell();
  45. this.value = false;
  46. this.render();
  47. }
  48. activate() {
  49. if (this.value === true) return this.bell();
  50. this.value = true;
  51. this.render();
  52. }
  53. delete() {
  54. this.deactivate();
  55. }
  56. left() {
  57. this.deactivate();
  58. }
  59. right() {
  60. this.activate();
  61. }
  62. down() {
  63. this.deactivate();
  64. }
  65. up() {
  66. this.activate();
  67. }
  68. next() {
  69. this.value = !this.value;
  70. this.fire();
  71. this.render();
  72. }
  73. _(c, key) {
  74. if (c === ' ') {
  75. this.value = !this.value;
  76. this.render();
  77. } else if (c === '1') {
  78. this.value = true;
  79. this.render();
  80. } else if (c === '0') {
  81. this.value = false;
  82. this.render();
  83. } else return this.bell();
  84. }
  85. render(first) {
  86. if (first) this.out.write(cursor.hide);
  87. this.out.write(
  88. erase.lines(first ? 1 : this.msg.split(/\n/g).length) +
  89. cursor.to(0) +
  90. [
  91. style.symbol(this.done, this.aborted),
  92. color.bold(this.msg),
  93. style.delimiter(this.done),
  94. this.value ? this.inactive : color.cyan.underline(this.inactive),
  95. color.gray('/'),
  96. this.value ? color.cyan.underline(this.active) : this.active
  97. ].join(' ')
  98. );
  99. }
  100. }
  101. module.exports = TogglePrompt;