checkbox.js 6.7 KB

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