autocomplete.js 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. 'use strict';
  2. const color = require('kleur');
  3. const Prompt = require('./prompt');
  4. const { erase, cursor } = require('sisteransi');
  5. const { style, clear, figures, wrap, entriesToDisplay } = require('../util');
  6. const getVal = (arr, i) => arr[i] && (arr[i].value || arr[i].title || arr[i]);
  7. const getTitle = (arr, i) => arr[i] && (arr[i].title || arr[i].value || arr[i]);
  8. const getIndex = (arr, valOrTitle) => {
  9. const index = arr.findIndex(el => el.value === valOrTitle || el.title === valOrTitle);
  10. return index > -1 ? index : undefined;
  11. };
  12. /**
  13. * TextPrompt Base Element
  14. * @param {Object} opts Options
  15. * @param {String} opts.message Message
  16. * @param {Array} opts.choices Array of auto-complete choices objects
  17. * @param {Function} [opts.suggest] Filter function. Defaults to sort by title
  18. * @param {Number} [opts.limit=10] Max number of results to show
  19. * @param {Number} [opts.cursor=0] Cursor start position
  20. * @param {String} [opts.style='default'] Render style
  21. * @param {String} [opts.fallback] Fallback message - initial to default value
  22. * @param {String} [opts.initial] Index of the default value
  23. * @param {Boolean} [opts.clearFirst] The first ESCAPE keypress will clear the input
  24. * @param {Stream} [opts.stdin] The Readable stream to listen to
  25. * @param {Stream} [opts.stdout] The Writable stream to write readline data to
  26. * @param {String} [opts.noMatches] The no matches found label
  27. */
  28. class AutocompletePrompt extends Prompt {
  29. constructor(opts={}) {
  30. super(opts);
  31. this.msg = opts.message;
  32. this.suggest = opts.suggest;
  33. this.choices = opts.choices;
  34. this.initial = typeof opts.initial === 'number'
  35. ? opts.initial
  36. : getIndex(opts.choices, opts.initial);
  37. this.select = this.initial || opts.cursor || 0;
  38. this.i18n = { noMatches: opts.noMatches || 'no matches found' };
  39. this.fallback = opts.fallback || this.initial;
  40. this.clearFirst = opts.clearFirst || false;
  41. this.suggestions = [];
  42. this.input = '';
  43. this.limit = opts.limit || 10;
  44. this.cursor = 0;
  45. this.transform = style.render(opts.style);
  46. this.scale = this.transform.scale;
  47. this.render = this.render.bind(this);
  48. this.complete = this.complete.bind(this);
  49. this.clear = clear('', this.out.columns);
  50. this.complete(this.render);
  51. this.render();
  52. }
  53. set fallback(fb) {
  54. this._fb = Number.isSafeInteger(parseInt(fb)) ? parseInt(fb) : fb;
  55. }
  56. get fallback() {
  57. let choice;
  58. if (typeof this._fb === 'number')
  59. choice = this.choices[this._fb];
  60. else if (typeof this._fb === 'string')
  61. choice = { title: this._fb };
  62. return choice || this._fb || { title: this.i18n.noMatches };
  63. }
  64. moveSelect(i) {
  65. this.select = i;
  66. if (this.suggestions.length > 0)
  67. this.value = getVal(this.suggestions, i);
  68. else this.value = this.fallback.value;
  69. this.fire();
  70. }
  71. async complete(cb) {
  72. const p = (this.completing = this.suggest(this.input, this.choices));
  73. const suggestions = await p;
  74. if (this.completing !== p) return;
  75. this.suggestions = suggestions
  76. .map((s, i, arr) => ({ title: getTitle(arr, i), value: getVal(arr, i), description: s.description }));
  77. this.completing = false;
  78. const l = Math.max(suggestions.length - 1, 0);
  79. this.moveSelect(Math.min(l, this.select));
  80. cb && cb();
  81. }
  82. reset() {
  83. this.input = '';
  84. this.complete(() => {
  85. this.moveSelect(this.initial !== void 0 ? this.initial : 0);
  86. this.render();
  87. });
  88. this.render();
  89. }
  90. exit() {
  91. if (this.clearFirst && this.input.length > 0) {
  92. this.reset();
  93. } else {
  94. this.done = this.exited = true;
  95. this.aborted = false;
  96. this.fire();
  97. this.render();
  98. this.out.write('\n');
  99. this.close();
  100. }
  101. }
  102. abort() {
  103. this.done = this.aborted = true;
  104. this.exited = false;
  105. this.fire();
  106. this.render();
  107. this.out.write('\n');
  108. this.close();
  109. }
  110. submit() {
  111. this.done = true;
  112. this.aborted = this.exited = false;
  113. this.fire();
  114. this.render();
  115. this.out.write('\n');
  116. this.close();
  117. }
  118. _(c, key) {
  119. let s1 = this.input.slice(0, this.cursor);
  120. let s2 = this.input.slice(this.cursor);
  121. this.input = `${s1}${c}${s2}`;
  122. this.cursor = s1.length+1;
  123. this.complete(this.render);
  124. this.render();
  125. }
  126. delete() {
  127. if (this.cursor === 0) return this.bell();
  128. let s1 = this.input.slice(0, this.cursor-1);
  129. let s2 = this.input.slice(this.cursor);
  130. this.input = `${s1}${s2}`;
  131. this.complete(this.render);
  132. this.cursor = this.cursor-1;
  133. this.render();
  134. }
  135. deleteForward() {
  136. if(this.cursor*this.scale >= this.rendered.length) return this.bell();
  137. let s1 = this.input.slice(0, this.cursor);
  138. let s2 = this.input.slice(this.cursor+1);
  139. this.input = `${s1}${s2}`;
  140. this.complete(this.render);
  141. this.render();
  142. }
  143. first() {
  144. this.moveSelect(0);
  145. this.render();
  146. }
  147. last() {
  148. this.moveSelect(this.suggestions.length - 1);
  149. this.render();
  150. }
  151. up() {
  152. if (this.select === 0) {
  153. this.moveSelect(this.suggestions.length - 1);
  154. } else {
  155. this.moveSelect(this.select - 1);
  156. }
  157. this.render();
  158. }
  159. down() {
  160. if (this.select === this.suggestions.length - 1) {
  161. this.moveSelect(0);
  162. } else {
  163. this.moveSelect(this.select + 1);
  164. }
  165. this.render();
  166. }
  167. next() {
  168. if (this.select === this.suggestions.length - 1) {
  169. this.moveSelect(0);
  170. } else this.moveSelect(this.select + 1);
  171. this.render();
  172. }
  173. nextPage() {
  174. this.moveSelect(Math.min(this.select + this.limit, this.suggestions.length - 1));
  175. this.render();
  176. }
  177. prevPage() {
  178. this.moveSelect(Math.max(this.select - this.limit, 0));
  179. this.render();
  180. }
  181. left() {
  182. if (this.cursor <= 0) return this.bell();
  183. this.cursor = this.cursor-1;
  184. this.render();
  185. }
  186. right() {
  187. if (this.cursor*this.scale >= this.rendered.length) return this.bell();
  188. this.cursor = this.cursor+1;
  189. this.render();
  190. }
  191. renderOption(v, hovered, isStart, isEnd) {
  192. let desc;
  193. let prefix = isStart ? figures.arrowUp : isEnd ? figures.arrowDown : ' ';
  194. let title = hovered ? color.cyan().underline(v.title) : v.title;
  195. prefix = (hovered ? color.cyan(figures.pointer) + ' ' : ' ') + prefix;
  196. if (v.description) {
  197. desc = ` - ${v.description}`;
  198. if (prefix.length + title.length + desc.length >= this.out.columns
  199. || v.description.split(/\r?\n/).length > 1) {
  200. desc = '\n' + wrap(v.description, { margin: 3, width: this.out.columns })
  201. }
  202. }
  203. return prefix + ' ' + title + color.gray(desc || '');
  204. }
  205. render() {
  206. if (this.closed) return;
  207. if (this.firstRender) this.out.write(cursor.hide);
  208. else this.out.write(clear(this.outputText, this.out.columns));
  209. super.render();
  210. let { startIndex, endIndex } = entriesToDisplay(this.select, this.choices.length, this.limit);
  211. this.outputText = [
  212. style.symbol(this.done, this.aborted, this.exited),
  213. color.bold(this.msg),
  214. style.delimiter(this.completing),
  215. this.done && this.suggestions[this.select]
  216. ? this.suggestions[this.select].title
  217. : this.rendered = this.transform.render(this.input)
  218. ].join(' ');
  219. if (!this.done) {
  220. const suggestions = this.suggestions
  221. .slice(startIndex, endIndex)
  222. .map((item, i) => this.renderOption(item,
  223. this.select === i + startIndex,
  224. i === 0 && startIndex > 0,
  225. i + startIndex === endIndex - 1 && endIndex < this.choices.length))
  226. .join('\n');
  227. this.outputText += `\n` + (suggestions || color.gray(this.fallback.title));
  228. }
  229. this.out.write(erase.line + cursor.to(0) + this.outputText);
  230. }
  231. }
  232. module.exports = AutocompletePrompt;