list.js 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. 'use strict';
  2. /**
  3. * `list` type prompt
  4. */
  5. const chalk = require('chalk');
  6. const figures = require('figures');
  7. const cliCursor = require('cli-cursor');
  8. const runAsync = require('run-async');
  9. const { flatMap, map, take, takeUntil } = require('rxjs/operators');
  10. const Base = require('./base');
  11. const observe = require('../utils/events');
  12. const Paginator = require('../utils/paginator');
  13. const incrementListIndex = require('../utils/incrementListIndex');
  14. class ListPrompt extends Base {
  15. constructor(questions, rl, answers) {
  16. super(questions, rl, answers);
  17. if (!this.opt.choices) {
  18. this.throwParamError('choices');
  19. }
  20. this.firstRender = true;
  21. this.selected = 0;
  22. const def = this.opt.default;
  23. // If def is a Number, then use as index. Otherwise, check for value.
  24. if (typeof def === 'number' && def >= 0 && def < this.opt.choices.realLength) {
  25. this.selected = def;
  26. } else if (typeof def !== 'number' && def != null) {
  27. const index = this.opt.choices.realChoices.findIndex(({ value }) => value === def);
  28. this.selected = Math.max(index, 0);
  29. }
  30. // Make sure no default is set (so it won't be printed)
  31. this.opt.default = null;
  32. const shouldLoop = this.opt.loop === undefined ? true : this.opt.loop;
  33. this.paginator = new Paginator(this.screen, { isInfinite: shouldLoop });
  34. }
  35. /**
  36. * Start the Inquiry session
  37. * @param {Function} cb Callback when prompt is done
  38. * @return {this}
  39. */
  40. _run(cb) {
  41. this.done = cb;
  42. const self = this;
  43. const events = observe(this.rl);
  44. events.normalizedUpKey.pipe(takeUntil(events.line)).forEach(this.onUpKey.bind(this));
  45. events.normalizedDownKey
  46. .pipe(takeUntil(events.line))
  47. .forEach(this.onDownKey.bind(this));
  48. events.numberKey.pipe(takeUntil(events.line)).forEach(this.onNumberKey.bind(this));
  49. events.line
  50. .pipe(
  51. take(1),
  52. map(this.getCurrentValue.bind(this)),
  53. flatMap((value) =>
  54. runAsync(self.opt.filter)(value, self.answers).catch((err) => err)
  55. )
  56. )
  57. .forEach(this.onSubmit.bind(this));
  58. // Init the prompt
  59. cliCursor.hide();
  60. this.render();
  61. return this;
  62. }
  63. /**
  64. * Render the prompt to screen
  65. * @return {ListPrompt} self
  66. */
  67. render() {
  68. // Render question
  69. let message = this.getQuestion();
  70. if (this.firstRender) {
  71. message += chalk.dim('(Use arrow keys)');
  72. }
  73. // Render choices or answer depending on the state
  74. if (this.status === 'answered') {
  75. message += chalk.cyan(this.opt.choices.getChoice(this.selected).short);
  76. } else {
  77. const choicesStr = listRender(this.opt.choices, this.selected);
  78. const indexPosition = this.opt.choices.indexOf(
  79. this.opt.choices.getChoice(this.selected)
  80. );
  81. const realIndexPosition =
  82. this.opt.choices.reduce((acc, value, i) => {
  83. // Dont count lines past the choice we are looking at
  84. if (i > indexPosition) {
  85. return acc;
  86. }
  87. // Add line if it's a separator
  88. if (value.type === 'separator') {
  89. return acc + 1;
  90. }
  91. let l = value.name;
  92. // Non-strings take up one line
  93. if (typeof l !== 'string') {
  94. return acc + 1;
  95. }
  96. // Calculate lines taken up by string
  97. l = l.split('\n');
  98. return acc + l.length;
  99. }, 0) - 1;
  100. message +=
  101. '\n' + this.paginator.paginate(choicesStr, realIndexPosition, this.opt.pageSize);
  102. }
  103. this.firstRender = false;
  104. this.screen.render(message);
  105. }
  106. /**
  107. * When user press `enter` key
  108. */
  109. onSubmit(value) {
  110. this.status = 'answered';
  111. // Rerender prompt
  112. this.render();
  113. this.screen.done();
  114. cliCursor.show();
  115. this.done(value);
  116. }
  117. getCurrentValue() {
  118. return this.opt.choices.getChoice(this.selected).value;
  119. }
  120. /**
  121. * When user press a key
  122. */
  123. onUpKey() {
  124. this.selected = incrementListIndex(this.selected, 'up', this.opt);
  125. this.render();
  126. }
  127. onDownKey() {
  128. this.selected = incrementListIndex(this.selected, 'down', this.opt);
  129. this.render();
  130. }
  131. onNumberKey(input) {
  132. if (input <= this.opt.choices.realLength) {
  133. this.selected = input - 1;
  134. }
  135. this.render();
  136. }
  137. }
  138. /**
  139. * Function for rendering list choices
  140. * @param {Number} pointer Position of the pointer
  141. * @return {String} Rendered content
  142. */
  143. function listRender(choices, pointer) {
  144. let output = '';
  145. let separatorOffset = 0;
  146. choices.forEach((choice, i) => {
  147. if (choice.type === 'separator') {
  148. separatorOffset++;
  149. output += ' ' + choice + '\n';
  150. return;
  151. }
  152. if (choice.disabled) {
  153. separatorOffset++;
  154. output += ' - ' + choice.name;
  155. output += ` (${
  156. typeof choice.disabled === 'string' ? choice.disabled : 'Disabled'
  157. })`;
  158. output += '\n';
  159. return;
  160. }
  161. const isSelected = i - separatorOffset === pointer;
  162. let line = (isSelected ? figures.pointer + ' ' : ' ') + choice.name;
  163. if (isSelected) {
  164. line = chalk.cyan(line);
  165. }
  166. output += line + ' \n';
  167. });
  168. return output.replace(/\n$/, '');
  169. }
  170. module.exports = ListPrompt;