UI for Zipcoin Blue

expand.js 5.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. /**
  2. * `rawlist` type prompt
  3. */
  4. var _ = require('lodash');
  5. var util = require('util');
  6. var chalk = require('chalk');
  7. var Base = require('./base');
  8. var Separator = require('../objects/separator');
  9. var observe = require('../utils/events');
  10. var Paginator = require('../utils/paginator');
  11. /**
  12. * Module exports
  13. */
  14. module.exports = Prompt;
  15. /**
  16. * Constructor
  17. */
  18. function Prompt() {
  19. Base.apply(this, arguments);
  20. if (!this.opt.choices) {
  21. this.throwParamError('choices');
  22. }
  23. this.validateChoices(this.opt.choices);
  24. // Add the default `help` (/expand) option
  25. this.opt.choices.push({
  26. key: 'h',
  27. name: 'Help, list all options',
  28. value: 'help'
  29. });
  30. this.opt.validate = function (choice) {
  31. if (choice == null) {
  32. return 'Please enter a valid command';
  33. }
  34. return choice !== 'help';
  35. };
  36. // Setup the default string (capitalize the default key)
  37. this.opt.default = this.generateChoicesString(this.opt.choices, this.opt.default);
  38. this.paginator = new Paginator();
  39. }
  40. util.inherits(Prompt, Base);
  41. /**
  42. * Start the Inquiry session
  43. * @param {Function} cb Callback when prompt is done
  44. * @return {this}
  45. */
  46. Prompt.prototype._run = function (cb) {
  47. this.done = cb;
  48. // Save user answer and update prompt to show selected option.
  49. var events = observe(this.rl);
  50. var validation = this.handleSubmitEvents(
  51. events.line.map(this.getCurrentValue.bind(this))
  52. );
  53. validation.success.forEach(this.onSubmit.bind(this));
  54. validation.error.forEach(this.onError.bind(this));
  55. this.keypressObs = events.keypress.takeUntil(validation.success)
  56. .forEach(this.onKeypress.bind(this));
  57. // Init the prompt
  58. this.render();
  59. return this;
  60. };
  61. /**
  62. * Render the prompt to screen
  63. * @return {Prompt} self
  64. */
  65. Prompt.prototype.render = function (error, hint) {
  66. var message = this.getQuestion();
  67. var bottomContent = '';
  68. if (this.status === 'answered') {
  69. message += chalk.cyan(this.answer);
  70. } else if (this.status === 'expanded') {
  71. var choicesStr = renderChoices(this.opt.choices, this.selectedKey);
  72. message += this.paginator.paginate(choicesStr, this.selectedKey, this.opt.pageSize);
  73. message += '\n Answer: ';
  74. }
  75. message += this.rl.line;
  76. if (error) {
  77. bottomContent = chalk.red('>> ') + error;
  78. }
  79. if (hint) {
  80. bottomContent = chalk.cyan('>> ') + hint;
  81. }
  82. this.screen.render(message, bottomContent);
  83. };
  84. Prompt.prototype.getCurrentValue = function (input) {
  85. if (!input) {
  86. input = this.rawDefault;
  87. }
  88. var selected = this.opt.choices.where({key: input.toLowerCase().trim()})[0];
  89. if (!selected) {
  90. return null;
  91. }
  92. return selected.value;
  93. };
  94. /**
  95. * Generate the prompt choices string
  96. * @return {String} Choices string
  97. */
  98. Prompt.prototype.getChoices = function () {
  99. var output = '';
  100. this.opt.choices.forEach(function (choice) {
  101. output += '\n ';
  102. if (choice.type === 'separator') {
  103. output += ' ' + choice;
  104. return;
  105. }
  106. var choiceStr = choice.key + ') ' + choice.name;
  107. if (this.selectedKey === choice.key) {
  108. choiceStr = chalk.cyan(choiceStr);
  109. }
  110. output += choiceStr;
  111. }.bind(this));
  112. return output;
  113. };
  114. Prompt.prototype.onError = function (state) {
  115. if (state.value === 'help') {
  116. this.selectedKey = '';
  117. this.status = 'expanded';
  118. this.render();
  119. return;
  120. }
  121. this.render(state.isValid);
  122. };
  123. /**
  124. * When user press `enter` key
  125. */
  126. Prompt.prototype.onSubmit = function (state) {
  127. this.status = 'answered';
  128. var choice = this.opt.choices.where({value: state.value})[0];
  129. this.answer = choice.short || choice.name;
  130. // Re-render prompt
  131. this.render();
  132. this.screen.done();
  133. this.done(state.value);
  134. };
  135. /**
  136. * When user press a key
  137. */
  138. Prompt.prototype.onKeypress = function () {
  139. this.selectedKey = this.rl.line.toLowerCase();
  140. var selected = this.opt.choices.where({key: this.selectedKey})[0];
  141. if (this.status === 'expanded') {
  142. this.render();
  143. } else {
  144. this.render(null, selected ? selected.name : null);
  145. }
  146. };
  147. /**
  148. * Validate the choices
  149. * @param {Array} choices
  150. */
  151. Prompt.prototype.validateChoices = function (choices) {
  152. var formatError;
  153. var errors = [];
  154. var keymap = {};
  155. choices.filter(Separator.exclude).forEach(function (choice) {
  156. if (!choice.key || choice.key.length !== 1) {
  157. formatError = true;
  158. }
  159. if (keymap[choice.key]) {
  160. errors.push(choice.key);
  161. }
  162. keymap[choice.key] = true;
  163. choice.key = String(choice.key).toLowerCase();
  164. });
  165. if (formatError) {
  166. throw new Error('Format error: `key` param must be a single letter and is required.');
  167. }
  168. if (keymap.h) {
  169. throw new Error('Reserved key error: `key` param cannot be `h` - this value is reserved.');
  170. }
  171. if (errors.length) {
  172. throw new Error('Duplicate key error: `key` param must be unique. Duplicates: ' +
  173. _.uniq(errors).join(', '));
  174. }
  175. };
  176. /**
  177. * Generate a string out of the choices keys
  178. * @param {Array} choices
  179. * @param {Number} defaultIndex - the choice index to capitalize
  180. * @return {String} The rendered choices key string
  181. */
  182. Prompt.prototype.generateChoicesString = function (choices, defaultIndex) {
  183. var defIndex = choices.realLength - 1;
  184. if (_.isNumber(defaultIndex) && this.opt.choices.getChoice(defaultIndex)) {
  185. defIndex = defaultIndex;
  186. }
  187. var defStr = this.opt.choices.pluck('key');
  188. this.rawDefault = defStr[defIndex];
  189. defStr[defIndex] = String(defStr[defIndex]).toUpperCase();
  190. return defStr.join('');
  191. };
  192. /**
  193. * Function for rendering checkbox choices
  194. * @param {String} pointer Selected key
  195. * @return {String} Rendered content
  196. */
  197. function renderChoices(choices, pointer) {
  198. var output = '';
  199. choices.forEach(function (choice) {
  200. output += '\n ';
  201. if (choice.type === 'separator') {
  202. output += ' ' + choice;
  203. return;
  204. }
  205. var choiceStr = choice.key + ') ' + choice.name;
  206. if (pointer === choice.key) {
  207. choiceStr = chalk.cyan(choiceStr);
  208. }
  209. output += choiceStr;
  210. });
  211. return output;
  212. }