checkbox.js 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. 'use strict';
  2. /**
  3. * `list` type prompt
  4. */
  5. var _ = {
  6. isArray: require('lodash/isArray'),
  7. map: require('lodash/map'),
  8. isString: require('lodash/isString'),
  9. };
  10. var chalk = require('chalk');
  11. var cliCursor = require('cli-cursor');
  12. var figures = require('figures');
  13. var { map, takeUntil } = require('rxjs/operators');
  14. var Base = require('./base');
  15. var observe = require('../utils/events');
  16. var Paginator = require('../utils/paginator');
  17. var 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. var events = observe(this.rl);
  45. var 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. var message = this.getQuestion();
  77. var bottomContent = '';
  78. if (!this.spaceKeyPressed) {
  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)';
  87. }
  88. // Render choices or answer depending on the state
  89. if (this.status === 'answered') {
  90. message += chalk.cyan(this.selection.join(', '));
  91. } else {
  92. var choicesStr = renderChoices(this.opt.choices, this.pointer);
  93. var indexPosition = this.opt.choices.indexOf(
  94. this.opt.choices.getChoice(this.pointer)
  95. );
  96. var realIndexPosition =
  97. this.opt.choices.reduce(function (acc, value, i) {
  98. // Dont count lines past the choice we are looking at
  99. if (i > indexPosition) {
  100. return acc;
  101. }
  102. // Add line if it's a separator
  103. if (value.type === 'separator') {
  104. return acc + 1;
  105. }
  106. var l = value.name;
  107. // Non-strings take up one line
  108. if (typeof l !== 'string') {
  109. return acc + 1;
  110. }
  111. // Calculate lines taken up by string
  112. l = l.split('\n');
  113. return acc + l.length;
  114. }, 0) - 1;
  115. message +=
  116. '\n' + this.paginator.paginate(choicesStr, realIndexPosition, this.opt.pageSize);
  117. }
  118. if (error) {
  119. bottomContent = chalk.red('>> ') + error;
  120. }
  121. this.screen.render(message, bottomContent);
  122. }
  123. /**
  124. * When user press `enter` key
  125. */
  126. onEnd(state) {
  127. this.status = 'answered';
  128. this.spaceKeyPressed = true;
  129. // Rerender prompt (and clean subline error)
  130. this.render();
  131. this.screen.done();
  132. cliCursor.show();
  133. this.done(state.value);
  134. }
  135. onError(state) {
  136. this.render(state.isValid);
  137. }
  138. getCurrentValue() {
  139. var choices = this.opt.choices.filter(function (choice) {
  140. return Boolean(choice.checked) && !choice.disabled;
  141. });
  142. this.selection = _.map(choices, 'short');
  143. return _.map(choices, 'value');
  144. }
  145. onUpKey() {
  146. this.pointer = incrementListIndex(this.pointer, 'up', this.opt);
  147. this.render();
  148. }
  149. onDownKey() {
  150. this.pointer = incrementListIndex(this.pointer, 'down', this.opt);
  151. this.render();
  152. }
  153. onNumberKey(input) {
  154. if (input <= this.opt.choices.realLength) {
  155. this.pointer = input - 1;
  156. this.toggleChoice(this.pointer);
  157. }
  158. this.render();
  159. }
  160. onSpaceKey() {
  161. this.spaceKeyPressed = true;
  162. this.toggleChoice(this.pointer);
  163. this.render();
  164. }
  165. onAllKey() {
  166. var shouldBeChecked = Boolean(
  167. this.opt.choices.find(function (choice) {
  168. return choice.type !== 'separator' && !choice.checked;
  169. })
  170. );
  171. this.opt.choices.forEach(function (choice) {
  172. if (choice.type !== 'separator') {
  173. choice.checked = shouldBeChecked;
  174. }
  175. });
  176. this.render();
  177. }
  178. onInverseKey() {
  179. this.opt.choices.forEach(function (choice) {
  180. if (choice.type !== 'separator') {
  181. choice.checked = !choice.checked;
  182. }
  183. });
  184. this.render();
  185. }
  186. toggleChoice(index) {
  187. var item = this.opt.choices.getChoice(index);
  188. if (item !== undefined) {
  189. this.opt.choices.getChoice(index).checked = !item.checked;
  190. }
  191. }
  192. }
  193. /**
  194. * Function for rendering checkbox choices
  195. * @param {Number} pointer Position of the pointer
  196. * @return {String} Rendered content
  197. */
  198. function renderChoices(choices, pointer) {
  199. var output = '';
  200. var separatorOffset = 0;
  201. choices.forEach(function (choice, i) {
  202. if (choice.type === 'separator') {
  203. separatorOffset++;
  204. output += ' ' + choice + '\n';
  205. return;
  206. }
  207. if (choice.disabled) {
  208. separatorOffset++;
  209. output += ' - ' + choice.name;
  210. output += ' (' + (_.isString(choice.disabled) ? choice.disabled : 'Disabled') + ')';
  211. } else {
  212. var line = getCheckbox(choice.checked) + ' ' + choice.name;
  213. if (i - separatorOffset === pointer) {
  214. output += chalk.cyan(figures.pointer + line);
  215. } else {
  216. output += ' ' + line;
  217. }
  218. }
  219. output += '\n';
  220. });
  221. return output.replace(/\n$/, '');
  222. }
  223. /**
  224. * Get the checkbox
  225. * @param {Boolean} checked - add a X or not to the checkbox
  226. * @return {String} Composited checkbox string
  227. */
  228. function getCheckbox(checked) {
  229. return checked ? chalk.green(figures.radioOn) : figures.radioOff;
  230. }
  231. module.exports = CheckboxPrompt;