list.js 5.0 KB

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