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.

278 lines
6.8 KiB

4 years ago
  1. 'use strict';
  2. /**
  3. * `list` type prompt
  4. */
  5. const _ = {
  6. isArray: require('lodash/isArray'),
  7. map: require('lodash/map'),
  8. isString: require('lodash/isString'),
  9. };
  10. const chalk = require('chalk');
  11. const cliCursor = require('cli-cursor');
  12. const figures = require('figures');
  13. const { map, takeUntil } = require('rxjs/operators');
  14. const Base = require('./base');
  15. const observe = require('../utils/events');
  16. const Paginator = require('../utils/paginator');
  17. const incrementListIndex = require('../utils/incrementListIndex');
  18. class CheckboxPrompt extends Base {
  19. constructor(questions, rl, answers) {
  20. super(questions, rl, answers);
  21. if (!this.opt.choices) {
  22. this.throwParamError('choices');
  23. }
  24. if (_.isArray(this.opt.default)) {
  25. this.opt.choices.forEach(function (choice) {
  26. if (this.opt.default.indexOf(choice.value) >= 0) {
  27. choice.checked = true;
  28. }
  29. }, this);
  30. }
  31. this.pointer = 0;
  32. // Make sure no default is set (so it won't be printed)
  33. this.opt.default = null;
  34. const shouldLoop = this.opt.loop === undefined ? true : this.opt.loop;
  35. this.paginator = new Paginator(this.screen, { isInfinite: shouldLoop });
  36. }
  37. /**
  38. * Start the Inquiry session
  39. * @param {Function} cb Callback when prompt is done
  40. * @return {this}
  41. */
  42. _run(cb) {
  43. this.done = cb;
  44. const events = observe(this.rl);
  45. const validation = this.handleSubmitEvents(
  46. events.line.pipe(map(this.getCurrentValue.bind(this)))
  47. );
  48. validation.success.forEach(this.onEnd.bind(this));
  49. validation.error.forEach(this.onError.bind(this));
  50. events.normalizedUpKey
  51. .pipe(takeUntil(validation.success))
  52. .forEach(this.onUpKey.bind(this));
  53. events.normalizedDownKey
  54. .pipe(takeUntil(validation.success))
  55. .forEach(this.onDownKey.bind(this));
  56. events.numberKey
  57. .pipe(takeUntil(validation.success))
  58. .forEach(this.onNumberKey.bind(this));
  59. events.spaceKey
  60. .pipe(takeUntil(validation.success))
  61. .forEach(this.onSpaceKey.bind(this));
  62. events.aKey.pipe(takeUntil(validation.success)).forEach(this.onAllKey.bind(this));
  63. events.iKey.pipe(takeUntil(validation.success)).forEach(this.onInverseKey.bind(this));
  64. // Init the prompt
  65. cliCursor.hide();
  66. this.render();
  67. this.firstRender = false;
  68. return this;
  69. }
  70. /**
  71. * Render the prompt to screen
  72. * @return {CheckboxPrompt} self
  73. */
  74. render(error) {
  75. // Render question
  76. let message = this.getQuestion();
  77. let bottomContent = '';
  78. if (!this.dontShowHints) {
  79. message +=
  80. '(Press ' +
  81. chalk.cyan.bold('<space>') +
  82. ' to select, ' +
  83. chalk.cyan.bold('<a>') +
  84. ' to toggle all, ' +
  85. chalk.cyan.bold('<i>') +
  86. ' to invert selection, and ' +
  87. chalk.cyan.bold('<enter>') +
  88. ' to proceed)';
  89. }
  90. // Render choices or answer depending on the state
  91. if (this.status === 'answered') {
  92. message += chalk.cyan(this.selection.join(', '));
  93. } else {
  94. const choicesStr = renderChoices(this.opt.choices, this.pointer);
  95. const indexPosition = this.opt.choices.indexOf(
  96. this.opt.choices.getChoice(this.pointer)
  97. );
  98. const realIndexPosition =
  99. this.opt.choices.reduce((acc, value, i) => {
  100. // Dont count lines past the choice we are looking at
  101. if (i > indexPosition) {
  102. return acc;
  103. }
  104. // Add line if it's a separator
  105. if (value.type === 'separator') {
  106. return acc + 1;
  107. }
  108. let l = value.name;
  109. // Non-strings take up one line
  110. if (typeof l !== 'string') {
  111. return acc + 1;
  112. }
  113. // Calculate lines taken up by string
  114. l = l.split('\n');
  115. return acc + l.length;
  116. }, 0) - 1;
  117. message +=
  118. '\n' + this.paginator.paginate(choicesStr, realIndexPosition, this.opt.pageSize);
  119. }
  120. if (error) {
  121. bottomContent = chalk.red('>> ') + error;
  122. }
  123. this.screen.render(message, bottomContent);
  124. }
  125. /**
  126. * When user press `enter` key
  127. */
  128. onEnd(state) {
  129. this.status = 'answered';
  130. this.dontShowHints = true;
  131. // Rerender prompt (and clean subline error)
  132. this.render();
  133. this.screen.done();
  134. cliCursor.show();
  135. this.done(state.value);
  136. }
  137. onError(state) {
  138. this.render(state.isValid);
  139. }
  140. getCurrentValue() {
  141. const choices = this.opt.choices.filter(
  142. (choice) => Boolean(choice.checked) && !choice.disabled
  143. );
  144. this.selection = _.map(choices, 'short');
  145. return _.map(choices, 'value');
  146. }
  147. onUpKey() {
  148. this.pointer = incrementListIndex(this.pointer, 'up', this.opt);
  149. this.render();
  150. }
  151. onDownKey() {
  152. this.pointer = incrementListIndex(this.pointer, 'down', this.opt);
  153. this.render();
  154. }
  155. onNumberKey(input) {
  156. if (input <= this.opt.choices.realLength) {
  157. this.pointer = input - 1;
  158. this.toggleChoice(this.pointer);
  159. }
  160. this.render();
  161. }
  162. onSpaceKey() {
  163. this.toggleChoice(this.pointer);
  164. this.render();
  165. }
  166. onAllKey() {
  167. const shouldBeChecked = Boolean(
  168. this.opt.choices.find((choice) => choice.type !== 'separator' && !choice.checked)
  169. );
  170. this.opt.choices.forEach((choice) => {
  171. if (choice.type !== 'separator') {
  172. choice.checked = shouldBeChecked;
  173. }
  174. });
  175. this.render();
  176. }
  177. onInverseKey() {
  178. this.opt.choices.forEach((choice) => {
  179. if (choice.type !== 'separator') {
  180. choice.checked = !choice.checked;
  181. }
  182. });
  183. this.render();
  184. }
  185. toggleChoice(index) {
  186. const item = this.opt.choices.getChoice(index);
  187. if (item !== undefined) {
  188. this.opt.choices.getChoice(index).checked = !item.checked;
  189. }
  190. }
  191. }
  192. /**
  193. * Function for rendering checkbox choices
  194. * @param {Number} pointer Position of the pointer
  195. * @return {String} Rendered content
  196. */
  197. function renderChoices(choices, pointer) {
  198. let output = '';
  199. let separatorOffset = 0;
  200. choices.forEach((choice, i) => {
  201. if (choice.type === 'separator') {
  202. separatorOffset++;
  203. output += ' ' + choice + '\n';
  204. return;
  205. }
  206. if (choice.disabled) {
  207. separatorOffset++;
  208. output += ' - ' + choice.name;
  209. output += ' (' + (_.isString(choice.disabled) ? choice.disabled : 'Disabled') + ')';
  210. } else {
  211. const line = getCheckbox(choice.checked) + ' ' + choice.name;
  212. if (i - separatorOffset === pointer) {
  213. output += chalk.cyan(figures.pointer + line);
  214. } else {
  215. output += ' ' + line;
  216. }
  217. }
  218. output += '\n';
  219. });
  220. return output.replace(/\n$/, '');
  221. }
  222. /**
  223. * Get the checkbox
  224. * @param {Boolean} checked - add a X or not to the checkbox
  225. * @return {String} Composited checkbox string
  226. */
  227. function getCheckbox(checked) {
  228. return checked ? chalk.green(figures.radioOn) : figures.radioOff;
  229. }
  230. module.exports = CheckboxPrompt;