forked from rickbergfalk/prompt-autocomplete
/
prompt-autocomplete.js
264 lines (242 loc) · 10.3 KB
/
prompt-autocomplete.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
var charm = require('charm')();
var keypress = require('keypress');
var tty = require('tty');
module.exports = askQuestion;
function askQuestion () {
// 1st arg is prompt question text
// 2nd is selection items
// 3rd will either be configuration, or a callback
// 4th will be a callback, if 3rd is configuration
var promptStart = arguments[0];
var items = arguments[1];
var config = (typeof arguments[2] == 'function' ? {} : arguments[2] || {});
var answerCallback = (typeof arguments[2] == 'function' ? arguments[2] : arguments[3]);
var maxAutocomplete = config.maxAutocomplete || process.stdout.rows - 2;
var highlightMode = config.highlightMode || "bright";
var forceToList = config.forceToList===undefined ? true : config.forceToList;
var candidates = [];
if (!promptStart) throw new Error("Prompt question is a required");
if (!items) throw new Error("Array of items is a required");
if (!answerCallback) throw new Error("A callback is required");
/* Stuff to get the stdout/in stuff working?
==============================================================================*/
charm.pipe(process.stdout);
if (typeof process.stdin.setRawMode == 'function') {
process.stdin.setRawMode(true);
} else {
tty.setRawMode(true);
}
process.stdin.resume();
/* Super basic Regular Expression Escaper function
Because the string we are autocompleting on might have some
Regular expression special characters...
==============================================================================*/
function escapeRegExp(string){
return string.replace(/([.*+?^${}()|\[\]\/\\])/g, "\\$1");
}
/* Get Candidates function
Basically all the search/filter stuff for the autocomplete
2 different methods of searching
- first search is on entire search string. These matches take priority
- second search is on partial search string, split on spaces
For example, lets say users searches for "charm fun".
An entry that contains the string "charm fun" is a higher-scoring match.
However, we will also show entries that either have "charm" or "fun"
==============================================================================*/
function getCandidates (querystr) {
candidates = [];
if (querystr === '' || !querystr) {
for (var i = 0; i < items.length; i++) {
candidates.push({text: items[i], matched: items[i]});
}
} else {
var splitQueryString = querystr.split(" ");
var escapedQueryString = escapeRegExp(querystr);
for (var x = 0; x < items.length; x++) {
var item = items[x];
// if item matches full query string, push it to the list of
// candidates.
// if not, test on partials
var reg = new RegExp(escapedQueryString, 'gi');
if (reg.test(item)) {
candidates.push({
text: item,
matched: item.replace(reg, '{DELIMITER}{MATCH}{DELIMITER}$&{DELIMITER}{NOMATCH}{DELIMITER}')
});
} else {
// escape each piece of the split query string
// then join together with pipes
// and then do a test/replace on that
var escapedSplitQueryString = "";
splitQueryString.forEach(function(qs) {
var escaped = escapeRegExp(qs);
if (escapedSplitQueryString) escapedSplitQueryString = escapedSplitQueryString + "|" + escaped;
else escapedSplitQueryString = escaped;
});
var splitReg = new RegExp(escapedSplitQueryString, 'gi');
if (splitReg.test(item)) {
candidates.push({
text: item,
matched: item.replace(splitReg, '{DELIMITER}{MATCH}{DELIMITER}$&{DELIMITER}{NOMATCH}{DELIMITER}')
});
}
}
}
}
return candidates;
}
/* Writing functions
==============================================================================*/
function writePrompt () {
charm.position(1,1);
charm.display('bright');
charm.write(promptStart);
charm.write(' ');
charm.display('reset');
}
charm.reset();
charm.cursor(false);
writePrompt();
var current = '';
var selectedIndex = -1;
function writeCurrent () {
// set charm to where user input would start
// erase whatever input is there, and write current
charm.position(promptStart.length + 2, 1);
charm.erase('end');
if (current) {
charm.position(promptStart.length + 2, 1);
charm.write(current);
}
candidates = getCandidates(current);
resetSelector();
writeCandidates();
}
var subsetStart = 0;
var candidateSubset = [];
function writeCandidates () {
// get candidate subset, in case we are rendering candidates beyond the max
candidateSubset = candidates.slice(subsetStart, subsetStart + maxAutocomplete);
// render the candidate subset;
for (var i = 0; i < maxAutocomplete; i++) {
charm.position(4, i + 2);
charm.erase('end');
if (candidateSubset[i]) {
var snippets = candidateSubset[i].matched.split('{DELIMITER}');
for (var s = 0; s < snippets.length; s++) {
var snippet = snippets[s];
if (snippet === '{MATCH}') {
charm.display(highlightMode);
} else if (snippet === '{NOMATCH}') {
charm.display('reset');
} else {
charm.write(snippet);
}
}
}
}
}
function resetSelector () {
// erase selected, if its on the screen
subsetStart = 0;
if (selectedIndex > -1) {
charm.position(3, selectedIndex + 2);
charm.erase('start');
}
if (candidates.length) {
selectedIndex = 0;
charm.position(1, selectedIndex + 2);
charm.write(' > ');
} else {
selectedIndex = -1;
}
}
function moveSelectorUp () {
if (selectedIndex === 0 && subsetStart > 0) {
subsetStart--;
writeCandidates();
} else {
// if selected index exists
// erase current selector and move selector up one
if (selectedIndex > -1) {
charm.position(3, selectedIndex + 2);
charm.erase('start');
selectedIndex--;
}
//writeCandidates();
// if someting is selected, render selector
if (selectedIndex > -1) {
charm.position(1, selectedIndex + 2);
charm.write(' > ');
}
}
}
function moveSelectorDown () {
if (selectedIndex == maxAutocomplete - 1 && (selectedIndex + subsetStart) < candidates.length - 1) {
// selected index is on last autocomplete selection
// instead of moving selection down, shift candidates and render list appropriately
subsetStart++;
writeCandidates();
} else if (selectedIndex < candidates.length - 1 && selectedIndex < maxAutocomplete - 1) {
// if selected index exists erase it
if (selectedIndex > -1) {
charm.position(3, selectedIndex + 2);
charm.erase('start');
}
selectedIndex++;
if (selectedIndex > -1) {
charm.position(1, selectedIndex + 2);
charm.write(' > ');
}
}
}
/* Keypress event handling
==============================================================================*/
// make `process.stdin` begin emitting "keypress" events
keypress(process.stdin);
// listen for the "keypress" event
process.stdin.on('keypress', function onKeypress (ch, key) {
if (key && key.ctrl && key.name == 'c') {
process.stdin.pause();
process.exit();
} else if (key && (key.name === 'tab' || key.name === 'left' || key.name === 'right')) {
// do nothing. (for now... these could do things later)
} else if (key && key.name === 'up') {
moveSelectorUp();
} else if (key && key.name === 'down') {
moveSelectorDown();
} else if (key && key.name === 'space') {
current = current + ' ';
writeCurrent();
} else if (key && key.name === 'backspace') {
current = current.slice(0, - 1);
writeCurrent();
} else if (key && key.name === 'return') {
// if a candiate is selected, return that candidate
// if only candidates are allowed and 1 candidate exists, return that candidate
// otherwise do nothing
if (candidateSubset[selectedIndex] && candidateSubset[selectedIndex].text) {
charm.position(1, maxAutocomplete + 3);
charm.cursor(true);
process.stdin.setRawMode(false);
process.stdin.pause();
charm.end();
process.stdin.removeListener('keypress', onKeypress);
answerCallback(null, candidateSubset[selectedIndex].text);
}
else if(selectedIndex==-1 && !forceToList){
process.stdin.setRawMode(false);
process.stdin.pause();
charm.end()
process.stdin.removeListener('keypress',onKeypress);
answerCallback(null,current)
}
} else {
// chances are this is just a regular key that should be typed to screen.
// so add it to the input and render it
current = current + ch;
writeCurrent();
}
});
writeCurrent();
}