-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
·564 lines (482 loc) · 15 KB
/
index.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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
#!/usr/bin/env node
const fs = require('fs');
const readline = require('readline');
const tty = require('tty');
const package = require('./package.json');
const READING_FROM_PIPE = !process.stdin.isTTY;
const WRITING_TO_PIPE = !process.stdout.isTTY;
const CALLED_VIA_CLI = require.main === module;
const TAB_WIDTH = 8;
const fullArgs = process.argv.join(' ');
const CLI_OPT_OUTPUT_HELP = / -h\b| --help\b/ .test(fullArgs);
const CLI_OPT_OUTPUT_INDEX = / -i\b/ .test(fullArgs);
const CLI_OPT_MULTILINE = / -m\b/ .test(fullArgs);
const CLI_OPT_OUTPUT_VERSION = / --version\b/ .test(fullArgs);
const CLI_OPT_HIDE_NUMBERS = / --hide-numbers\b/ .test(fullArgs);
const CLI_OPT_PRESERVE_ORDER = / --preserve-order\b/ .test(fullArgs);
const CLI_OPT_COMPACT = / -c\b| --compact\b/ .test(fullArgs);
const CLI_OPT_SKIP_BLANKS = / --skip-blanks\b/ .test(fullArgs);
const CLI_OPT_NO_COLOR = / --no-color\b/ .test(fullArgs);
const CLI_OPT_LOCK_LINES = / --lock-lines\b/ .test(fullArgs);
const parseArg = pattern => {
const res = pattern.exec(fullArgs);
return res ? res[1] : null;
}
const CLI_ARG_SKIP_CHAR = parseArg(/ --skip-char=(\S)(?:\s|$)/);
if (CLI_OPT_OUTPUT_HELP) {
process.stdout.write(`
Usage: ${ package.name } [OPTIONS]
${ package.description }
Options:
-h, --help output help
-i output line index instead of line
enables --lock-lines
-m enable multiple line selection
--hide-numbers hide selection number prefix
--preserve-order output lines in order of selection
-c, --compact separate options by tabs instead of newlines
--version output version
--skip-blanks skip over empty lines
--skip-char=[CHARACTER]
skip lines that start with CHARACTER
--no-color uses text instead of colors to show state
--lock-lines prevent use of move commands (u/d)
Controls:
up, left move cursor up
down, right move cursor down
q quit / cancel
u move highlighted line up
d move highlighted line down
Controls (single mode):
c, s, enter output highlighted line
Controls (multi mode):
s, enter add highlighted line to selection
shift + s to select range
c output selected lines
`);
return;
}
if (CLI_OPT_OUTPUT_VERSION) {
process.stdout.write(`
${ package.version }
`);
return;
}
const progOpts = {
};
function setProgramOptions(opts) {
opts = opts || {};
progOpts.multiline = 'multiline' in opts ? opts.multiline : CLI_OPT_MULTILINE;
progOpts.outputIndex = 'outputIndex' in opts ? opts.outputIndex : CLI_OPT_OUTPUT_INDEX;
progOpts.hideNumbers = 'hideNumbers' in opts ? opts.hideNumbers : CLI_OPT_HIDE_NUMBERS;
progOpts.preserveOrder = 'preserveOrder' in opts ? opts.preserveOrder : CLI_OPT_PRESERVE_ORDER;
progOpts.compact = 'compact' in opts ? opts.compact : CLI_OPT_COMPACT;
progOpts.skipBlanks = 'skipBlanks' in opts ? opts.skipBlanks : CLI_OPT_SKIP_BLANKS;
progOpts.noColor = 'noColor' in opts ? opts.noColor : CLI_OPT_NO_COLOR;
progOpts.lockLines = 'lockLines' in opts ? opts.lockLines : CLI_OPT_LOCK_LINES || CLI_OPT_OUTPUT_INDEX;
progOpts.skipChar = 'skipChar' in opts ? opts.skipChar : CLI_ARG_SKIP_CHAR;
if (progOpts.noColor) {
setNoColorStyles();
} else {
setDefaultStyles();
}
}
const ACTIONS = {
'up' : 'cursorUp',
'down' : 'cursorDown',
'left' : 'cursorUp',
'right' : 'cursorDown',
'return' : 'select',
's' : 'select',
'\u0003' : 'quit', // escape
'q' : 'quit',
'c' : 'continue',
'u' : 'moveUp',
'd' : 'moveDown',
};
const getAction = (str, key) => {
const action = ACTIONS[str] || ACTIONS[key.name];
switch (action) {
case 'moveUp': // intentional
case 'moveDown': {
if (progOpts.lockLines) {
return;
}
}
default: return action;
}
}
let ttyin;
let ttyout;
const getRows = () => ttyout.rows || process.stdout.rows || 10;
const getCols = () => ttyout.columns || process.stdout.columns || 50;
function getHeight() {
const rows = getRows() - 2;
if (progOpts.compact) {
const chars =
choices.map(option => option.length + TAB_WIDTH - (option.length % TAB_WIDTH))
.reduce((sum, width) => sum + width);
const optionRows = Math.ceil(chars / getCols()) - 1;
return Math.min(optionRows, rows);
} else {
return Math.min(choices.length, rows);
}
}
// https://en.wikipedia.org/wiki/ANSI_escape_code
const AnsiColorCodes = {
reset : '[0m',
bold : '[1m',
faint : '[2m',
black : '[30m',
magenta : '[35m',
yellow : '[33m',
bgMagenta : '[45m',
bgWhite : '[47m',
bgBrightMagenta : '[105m',
bgBrightWhite : '[107m',
};
const Style = new Proxy(AnsiColorCodes, {
get(target, property, reciever) {
return `\x1b${target[property]}`;
},
});
const id = text => text;
const pinkHighlight = text => Style.bgBrightMagenta + Style.black + text + Style.reset;
const whiteHighlight = text => Style.bgBrightWhite + Style.black + text + Style.reset;
const pink = text => Style.magenta + text + Style.reset;
const faint = text => Style.faint + text + Style.reset;
const clear = text => text + Style.reset;
let letStyleLength;
let styleUnselected;
let styleHighlightedSelected;
let styleHighlighted;
let styleSelected;
let unselectableStyle;
function setDefaultStyles() {
// Important that all function here pad the line length by styleLength
styleLength = 0;
styleUnselected = id;
styleHighlightedSelected = pinkHighlight;
styleHighlighted = whiteHighlight;
styleSelected = pink;
unselectableStyle = faint;
}
function setNoColorStyles() {
// Important that all functions here pad the line length by styleLength
if (progOpts.multiline) {
styleLength = 5;
styleUnselected = text => ` [ ] ${text}`;
styleHighlightedSelected = text => `→[X] ${text}`;
styleHighlighted = text => `→[ ] ${text}`;
styleSelected = text => ` [X] ${text}`;
unselectableStyle = text => faint(' --- ') + text;
} else {
styleLength = 2;
styleUnselected = text => ` ${text}`;
styleHighlightedSelected = text => `→ ${text}`;
styleHighlighted = text => `→ ${text}`;
styleSelected = text => ` ${text}`;
unselectableStyle = text => faint(' -') + text;
}
}
let selected;
let lastSelected;
let selectionIndex;
let rowOffset;
let multiSelectedOptions;
function resetState() {
selected = -1;
lastSelected = 0;
selectionIndex = 1;
rowOffset = 0;
multiSelectedOptions = {};
}
let choices;
let progResolve;
if (CALLED_VIA_CLI) {
setProgramOptions();
cliMain();
} else {
module.exports = async function(passedChoices, options) {
if (progResolve !== undefined) {
throw new Error('seline already in use!');
}
resetState();
choices = passedChoices;
setProgramOptions(options);
return new Promise((resolve, reject) => {
progResolve = resolve;
main();
});
};
}
async function cliMain() {
resetState();
choices = await readChoices();
main();
}
function main() {
ttyin = new tty.ReadStream(fs.openSync('/dev/tty', 'r'));
ttyout = new tty.WriteStream(fs.openSync('/dev/tty', 'w'));
// TODO - commenting this out will hide the input line, giving seline
// full screen while its running. Not sure if I want this, so leaving
// as-is for now.
writeScreen();
// Select the first item in the list
moveCursor(1, true);
ttyin.setRawMode(true);
readline.emitKeypressEvents(ttyin);
ttyin.on('keypress', handleInput);
}
async function readChoices() {
return new Promise((resolve, reject) => {
const lines = [];
const input = process.stdin;
const rl = readline.createInterface({ input });
rl.on('line', chunk => lines.push(chunk));
rl.on('close', () => resolve(lines));
});
}
function writeScreen() {
if (progOpts.compact) {
ttyout.write(
choices.map(formatLine).join('')
);
} else {
ttyout.write(
choices.slice(rowOffset, rowOffset + getRows() - 2).map(formatLine).join('')
);
}
}
function formatLine(option, optionIndex) {
const i = optionIndex + rowOffset;
// Determine how to render the option text
const isHightlighted = i === selected;
const isMultiSelected = !!multiSelectedOptions[i];
let line = option.trimRight();
let fn = styleUnselected;
if (isHightlighted && isMultiSelected) {
fn = styleHighlightedSelected;
} else if (isHightlighted) {
fn = styleHighlighted;
} else if (isMultiSelected) {
fn = styleSelected;
} else if (isLineUnselectable(line)) {
fn = unselectableStyle;
}
if (!progOpts.compact) {
if (progOpts.preserveOrder && isMultiSelected) {
line = `(${multiSelectedOptions[i]}) ${line}`;
}
if (!progOpts.hideNumbers) {
line = `${i}: ${line}`;
}
}
const terminal = progOpts.compact ? '\t' : '\n';
const padding = progOpts.compact ? 0 : getCols() - (line.length + styleLength);
if (padding >= 0) {
return `${fn(line)}${' '.repeat(padding)}${terminal}`;
} else {
return `${clear(fn(line.slice(0, padding)))}${terminal}`;
}
}
function handleInput(str, key) {
const action = getAction(str, key);
switch (action) {
case 'quit':
return end();
case 'cursorUp':
return moveCursor(-1, true);
case 'cursorDown':
return moveCursor(1, true);
case 'moveUp':
return moveSelection(-1);
case 'moveDown':
return moveSelection(1);
case 'select': {
return handleSelect(!!key.shift);
}
case 'continue':
return handleContinue();
default: {
const val = parseInt(str, 10);
if (val == str) return moveCursor(val - selected);
}
}
}
function end(output) {
const height = getHeight();
if (progOpts.compact) {
readline.cursorTo(ttyout, 0);
}
readline.moveCursor(ttyout, 0, -height);
readline.clearScreenDown(ttyout);
if (CALLED_VIA_CLI) {
if (output) {
process.stdout.write(`${output}\n`);
}
} else {
progResolve(output);
choices = undefined;
progResolve = undefined;
setProgramOptions();
}
if (CALLED_VIA_CLI) {
process.exit();
} else {
try {
ttyin.destroy();
ttyout.destroy();
} catch (err) {
console.warn('Could not destroy tty streams! Killing process');
process.exit();
}
}
}
function isLineUnselectable(line) {
if (progOpts.skipBlanks && line === '') {
return true;
} else if (progOpts.skipChar === line[0]) {
return true;
}
return false;
}
function moveCursor(dir, doRecursiveMove) {
const _selected = selected + dir;
if (_selected < 0 || _selected >= choices.length) {
return;
}
if (isLineUnselectable(choices[_selected])) {
if (doRecursiveMove) {
return moveCursor(dir + (dir < 0 ? -1 : 1), doRecursiveMove);
} else {
return;
}
}
if (_selected === selected) {
return;
}
const rows = getRows() - 2;
const height = getHeight();
// TODO - scolling in COMPACT mode is probably broken
if (dir < 0 && _selected < rowOffset) {
rowOffset = _selected;
} else if (dir > 0 && _selected >= rowOffset + rows) {
rowOffset = _selected - rows + 1;
}
selected = _selected;
if (progOpts.compact) {
readline.cursorTo(ttyout, 0);
}
readline.moveCursor(ttyout, 0, -height);
writeScreen(choices, selected, multiSelectedOptions, rowOffset);
}
function moveSelection(dir) {
const _selected = Math.min(choices.length - 1, Math.max(0, selected + dir));
if (selected === _selected) {
return;
}
const currentValue = choices[selected];
choices[selected] = choices[_selected];
choices[_selected] = currentValue;
return moveCursor(dir);
}
function handleSelect(shiftSelect) {
if (!progOpts.multiline) {
return handleContinue();
}
height = getHeight();
if (!shiftSelect || lastSelected === selected) {
const isSelected = !!multiSelectedOptions[selected];
applySelection(selected, isSelected);
} else {
const isSelected = !multiSelectedOptions[lastSelected];
const iterDirection = selected > lastSelected ? 1 : -1;
for (let i = lastSelected; i !== selected; i += iterDirection) {
applySelection(i, isSelected);
}
applySelection(selected, isSelected);
}
lastSelected = selected;
if (progOpts.multiline && progOpts.preserveOrder) {
let entries = Object.entries(multiSelectedOptions).filter(([key, val]) => !!val);
entries.sort((a, b) => {
return a[1] - b[1];
});
entries.forEach(([key], index) => {
multiSelectedOptions[key] = index + 1;
});
selectionIndex = entries.length + 1;
}
if (progOpts.compact) {
readline.cursorTo(ttyout, 0);
}
readline.moveCursor(ttyout, 0, -height);
writeScreen(choices, selected, multiSelectedOptions, rowOffset);
}
function applySelection(index, isSelected) {
if (!isSelected && isLineUnselectable(choices[index])) {
return;
}
if (isSelected) {
multiSelectedOptions[index] = 0;
} else {
multiSelectedOptions[index] = selectionIndex;
selectionIndex += 1;
}
}
function handleContinue() {
const output = getOutput();
end(output);
}
function getOutput() {
if (progOpts.outputIndex) {
if (progOpts.multiline) {
let entries;
if (progOpts.preserveOrder) {
entries = [];
Object.entries(multiSelectedOptions)
.forEach(([lineIndex, orderIndex]) => {
// value of 0 for orderIndex means it was unselected
if (!orderIndex) return;
// selection order is stored 1-indexed
entries[orderIndex - 1] = parseInt(lineIndex, 10);
});
} else {
entries = Object.entries(multiSelectedOptions)
.filter(([key, value]) => value)
.map(([key, value]) => parseInt(key, 10));
}
if (CALLED_VIA_CLI) {
return entries.join('\n');
} else {
return entries;
}
} else {
return selected;
}
} else {
if (progOpts.multiline) {
let entries;
if (progOpts.preserveOrder) {
entries = [];
Object.entries(multiSelectedOptions).forEach(([lineIndex, orderIndex]) => {
// value of 0 for orderIndex means it was unselected
if (!orderIndex) return;
// selection order is stored 1-indexed
entries[orderIndex - 1] = choices[lineIndex];
});
entries = entries.filter(val => !!val);
} else {
entries = choices.filter((_, i) => !!multiSelectedOptions[i]);
}
if (CALLED_VIA_CLI) {
return entries.join('\n');
} else {
return entries;
}
} else {
return choices[selected];
}
}
}