list.js 5.2 KB

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