You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

109 lines
2.2 KiB

4 years ago
  1. 'use strict';
  2. const BooleanPrompt = require('../types/boolean');
  3. class TogglePrompt extends BooleanPrompt {
  4. async initialize() {
  5. await super.initialize();
  6. this.value = this.initial = !!this.options.initial;
  7. this.disabled = this.options.disabled || 'no';
  8. this.enabled = this.options.enabled || 'yes';
  9. await this.render();
  10. }
  11. reset() {
  12. this.value = this.initial;
  13. this.render();
  14. }
  15. delete() {
  16. this.alert();
  17. }
  18. toggle() {
  19. this.value = !this.value;
  20. this.render();
  21. }
  22. enable() {
  23. if (this.value === true) return this.alert();
  24. this.value = true;
  25. this.render();
  26. }
  27. disable() {
  28. if (this.value === false) return this.alert();
  29. this.value = false;
  30. this.render();
  31. }
  32. up() {
  33. this.toggle();
  34. }
  35. down() {
  36. this.toggle();
  37. }
  38. right() {
  39. this.toggle();
  40. }
  41. left() {
  42. this.toggle();
  43. }
  44. next() {
  45. this.toggle();
  46. }
  47. prev() {
  48. this.toggle();
  49. }
  50. dispatch(ch = '', key) {
  51. switch (ch.toLowerCase()) {
  52. case ' ':
  53. return this.toggle();
  54. case '1':
  55. case 'y':
  56. case 't':
  57. return this.enable();
  58. case '0':
  59. case 'n':
  60. case 'f':
  61. return this.disable();
  62. default: {
  63. return this.alert();
  64. }
  65. }
  66. }
  67. format() {
  68. let active = str => this.styles.primary.underline(str);
  69. let value = [
  70. this.value ? this.disabled : active(this.disabled),
  71. this.value ? active(this.enabled) : this.enabled
  72. ];
  73. return value.join(this.styles.muted(' / '));
  74. }
  75. async render() {
  76. let { size } = this.state;
  77. let header = await this.header();
  78. let prefix = await this.prefix();
  79. let separator = await this.separator();
  80. let message = await this.message();
  81. let output = await this.format();
  82. let help = (await this.error()) || (await this.hint());
  83. let footer = await this.footer();
  84. let prompt = [prefix, message, separator, output].join(' ');
  85. this.state.prompt = prompt;
  86. if (help && !prompt.includes(help)) prompt += ' ' + help;
  87. this.clear(size);
  88. this.write([header, prompt, footer].filter(Boolean).join('\n'));
  89. this.write(this.margin[2]);
  90. this.restore();
  91. }
  92. }
  93. module.exports = TogglePrompt;