toggle.js 2.3 KB

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