checkbox.js 6.6 KB

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