-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
310 lines (260 loc) · 8.5 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
/**
* `checkbox-search` type prompt
*/
const _ = require('lodash')
const util = require('util')
const chalk = require('chalk')
const cliCursor = require('cli-cursor')
const figures = require('figures')
const Base = require('inquirer/lib/prompts/base')
const observe = require('inquirer/lib/utils/events')
const readline = require('inquirer/lib/utils/readline')
const Paginator = require('inquirer/lib/utils/paginator')
const Choices = require('inquirer/lib/objects/choices')
/**
* Module exports
*/
module.exports = Prompt
/**
* Constructor
*/
function Prompt() {
Base.apply(this, arguments)
if (!this.opt.source) {
this.throwParamError('source')
}
this.currentChoices = []
this.firstRender = true
// Make sure no default is set (so it won't be printed)
this.opt.default = null
this.paginator = new Paginator()
}
util.inherits(Prompt, Base)
/**
* Start the Inquiry session
* @param {Function} cb Callback when prompt is done
* @return {this}
*/
Prompt.prototype._run = function (cb) {
this.done = cb
const self = this
const events = observe(this.rl)
const validation = this.handleSubmitEvents(
events.line.map(this.getCurrentValue.bind(this))
)
validation.success.forEach(this.onEnd.bind(this))
validation.error.forEach(this.onError.bind(this))
events.keypress.takeWhile(dontHaveAnswer).forEach(self.onKeypress.bind(this))
function dontHaveAnswer() {
return !self.answer
}
//call once at init
self.search(null)
return this
}
/**
* Render the prompt to screen
* @return {Prompt} self
*/
Prompt.prototype.render = function (error) {
// Render question
let message = this.getQuestion()
let bottomContent = ''
if (this.firstRender) {
message += '(Type to filter, press ' + chalk.cyan.bold('<right arrow>') + ' to select, ' + chalk.cyan.bold('<shift>') + '+' + chalk.cyan.bold('<right arrow>') + ' to toggle all, ' + chalk.cyan.bold('<ctrl>') + '+' + chalk.cyan.bold('<right arrow>') + ' to inverse selection)'
// store initial choices to be referenced with selections and new searches
this.initialChoices = this.currentChoices
}
if (this.status === 'answered') {
message += chalk.cyan(this.shortAnswer || this.answerName || this.answer)
} else if (this.searching) {
message += this.rl.line
bottomContent += ' ' + chalk.dim('Searching...')
} else if (this.currentChoices.length) {
const choicesStr = renderCurrentChoices(this.initialChoices, this.currentChoices, this.selected)
message += this.rl.line
bottomContent += this.paginator.paginate(choicesStr, this.selected, this.opt.pageSize)
} else {
message += this.rl.line
bottomContent += ' ' + chalk.yellow('No results...')
}
if (error) {
bottomContent = chalk.red('>> ') + error
}
this.firstRender = false
this.screen.render(message, bottomContent)
}
/**
* Capture all key presses
* @param {Object} e The fired event
*/
Prompt.prototype.onKeypress = function(e) {
let len
const keyName = (e.key && e.key.name) || undefined
const ctrlModifier = e.key.ctrl
const shiftModifier = e.key.shift
if (keyName === 'down') {
len = this.currentChoices.length
this.selected = (this.selected < len - 1) ? this.selected + 1 : 0
this.ensureSelectedInRange()
this.render()
readline.up(this.rl, 2)
} else if (keyName === 'up') {
len = this.currentChoices.length
this.selected = (this.selected > 0) ? this.selected - 1 : len - 1
this.ensureSelectedInRange()
this.render()
} else if (keyName === 'right') {
if (shiftModifier) {
this.onAllKey()
this.render()
} else if (ctrlModifier) {
this.onInverseKey()
this.render()
} else {
this.toggleChoice(this.selected)
this.render()
}
} else {
this.render() //render input automatically
// Only search if input has actually changed, not because of other keypresses
if (this.lastSearchTerm !== this.rl.line) {
this.search(this.rl.line) //trigger new search
}
}
}
Prompt.prototype.ensureSelectedInRange = function() {
const selectedIndex = Math.min(this.selected, this.currentChoices.length) //not above currentChoices length - 1
this.selected = Math.max(selectedIndex, 0) //not below 0
}
/**
* Create new this.currentChoices based on search term
* @param {String} searchTerm The string to filter by
*/
Prompt.prototype.search = function(searchTerm) {
const self = this
self.selected = 0
//only render searching state after first time
if (self.searchedOnce) {
self.searching = true
self.currentChoices = new Choices([])
self.render() //now render current searching state
} else {
self.searchedOnce = true
}
self.lastSearchTerm = searchTerm
const thisPromise = self.opt.source(self.answers, searchTerm)
//store this promise for check in the callback
self.lastPromise = thisPromise
return thisPromise.then(function inner(choices) {
//if another search is triggered before the current search finishes, don't set results
if (thisPromise !== self.lastPromise) return
choices = new Choices(choices.filter(function(choice) {
return choice.type !== 'separator'
}))
self.currentChoices = choices
self.searching = false
self.render()
})
}
Prompt.prototype.onAllKey = function () {
const self = this
// return true if at least one currentChoice (from matching initialChoice) is not checked
const shouldBeChecked = Boolean(this.currentChoices.choices.find(currentChoice => {
if (currentChoice.type !== 'separator') {
for (const initialChoice of self.initialChoices.choices) {
if (initialChoice.name === currentChoice.name) {
return !initialChoice.checked
}
}
}
return false
}))
this.currentChoices.choices.forEach(currentChoice => {
if (currentChoice.type !== 'separator') {
for (const initialChoice of self.initialChoices.choices) {
if (initialChoice.name === currentChoice.name) {
initialChoice.checked = shouldBeChecked
}
}
}
})
}
Prompt.prototype.onInverseKey = function () {
const self = this
this.currentChoices.choices.forEach(currentChoice => {
if (currentChoice.type !== 'separator') {
for (const initialChoice of self.initialChoices.choices) {
if (currentChoice.name === initialChoice.name) {
initialChoice.checked = !initialChoice.checked
}
}
}
})
}
Prompt.prototype.toggleChoice = function (index) {
const currentChoice = this.currentChoices.choices[index]
if (currentChoice !== undefined) {
for (const initialChoice of this.initialChoices.choices) {
if (currentChoice.name === initialChoice.name) {
initialChoice.checked = !initialChoice.checked
}
}
}
}
/**
* When `enter` key is pressed
*/
Prompt.prototype.onEnd = function (state) {
this.status = 'answered'
// Rerender prompt (and clean subline error)
this.render()
this.screen.done()
cliCursor.show()
this.done(state.value)
}
Prompt.prototype.onError = function (state) {
this.render(state.isValid)
}
Prompt.prototype.getCurrentValue = function () {
const choices = this.initialChoices.filter(function (choice) {
return Boolean(choice.checked) && !choice.disabled
})
this.selection = _.map(choices, 'short')
return _.map(choices, 'value')
}
/**
* Get the checkbox
* @param {Boolean} checked - add a X or not to the checkbox
* @return {String} Composited checkbox string
*/
function getCheckbox(checked) {
return checked ? chalk.green(figures.radioOn) : figures.radioOff
}
/**
* Function for rendering current choices to screen
* @param {Array} initialChoices Initial choices from first render
* @param {Array} currentChoices Current choices to be displayed
* @param {Number} pointer Position of the pointer
* @return {String} Rendered content
*/
function renderCurrentChoices(initialChoices, currentChoices, pointer) {
let output = ''
let separatorOffset = 0
currentChoices.forEach((currentChoice, i) => {
if (currentChoice.type === 'separator') {
separatorOffset++
output += ' ' + currentChoice + '\n'
return
}
const isSelected = (i - separatorOffset === pointer)
output += isSelected ? chalk.cyan(figures.pointer) : ' '
for (const initialChoice of initialChoices.choices) {
if (currentChoice.name === initialChoice.name) {
output += getCheckbox(initialChoice.checked) + ' ' + (initialChoice.checked ? chalk.cyan(initialChoice.name) : initialChoice.name)
}
}
output += ' \n'
})
return output.replace(/\n$/, '')
}