-
Notifications
You must be signed in to change notification settings - Fork 1
/
cliSelect.js
77 lines (63 loc) · 1.7 KB
/
cliSelect.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
const readline = require('readline')
// Get process.stdin as the standard input object.
readline.emitKeypressEvents(process.stdin)
process.stdin.setRawMode(true)
// Set input character encoding.
process.stdin.setEncoding('utf-8')
process.on('SIGINT', () => {
console.log('exit!!!!');
process.exit()
})
let choice = 0
function getOptions (options) {
return options.map((op, i) => {
return `[${i === choice ? '✔' : ' '}] ${op}`
})
}
function printSelect (label, options) {
console.log(label)
console.log(getOptions(options).join('\n'))
}
function updateScreen (label, options) {
const msg = [
label,
...options
].join('\n').split('\n')
readline.cursorTo(process.stdout, 0)
readline.moveCursor(process.stdout, 0, -msg.length)
readline.clearScreenDown(process.stdout)
}
module.exports = {
select: (label, options) => {
printSelect(label, options)
return new Promise((resolve, reject) => {
process.stdin.on('keypress', (key, data) => {
switch (data.name) {
case 'up':
choice--
break
case 'down':
choice++
break
case 'return':
process.stdin.setRawMode(false)
process.stdin.removeAllListeners()
resolve(choice)
return false
default:
if (data.ctrl && data.name === 'c') {
process.exit()
} else {
console.log('key', key)
console.log('data', data)
}
break
}
choice = Math.max(choice, 0)
choice = Math.min(choice, options.length - 1)
updateScreen(label, options)
printSelect(label, options)
})
})
}
}