tis-cli前端项目快速搭建命令行工具
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.

214 lines
5.2 KiB

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