-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathprompt.ts
760 lines (622 loc) · 24.4 KB
/
prompt.ts
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
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
import colors from 'ansi-colors'
import stripAnsi from 'strip-ansi'
import ArrayPrompt from 'enquirer/lib/types/array'
import utils from 'enquirer/lib/utils'
import fuzzy from 'fuzzy'
import {
ChoiceInPrompt,
ScaleWithIndex,
ScaleWithName,
KeyPressEvent,
ExecutionGroup,
IRushSelect
} from './interfaces'
import { padReplace } from './string-utils'
class RushSelect extends ArrayPrompt implements IRushSelect {
constructor(options = {}) {
// @ts-expect-error ts-migrate(2339) FIXME: Property 'ignoreText' does not exist on type '{}'.
options.ignoreText = options.ignoreText || 'ignore'
// @ts-expect-error ts-migrate(2339) FIXME: Property 'uncategorizedText' does not exist on typ... Remove this comment to see the full error message
options.uncategorizedText = options.uncategorizedText || 'uncategorized'
// @ts-expect-error ts-migrate(2339) FIXME: Property 'scale' does not exist on type '{}'.
options.scale.unshift({
// @ts-expect-error ts-migrate(2339) FIXME: Property 'ignoreText' does not exist on type '{}'.
name: options.ignoreText
})
super(options)
// @ts-expect-error ts-migrate(2339) FIXME: Property 'messageWidth' does not exist on type '{}... Remove this comment to see the full error message
this.widths = [].concat(options.messageWidth || 50)
// @ts-expect-error ts-migrate(2339) FIXME: Property 'align' does not exist on type '{}'.
this.align = [].concat(options.align || 'left')
// @ts-expect-error ts-migrate(2339) FIXME: Property 'linebreak' does not exist on type '{}'.
this.linebreak = options.linebreak || false
// @ts-expect-error ts-migrate(2339) FIXME: Property 'edgeLength' does not exist on type '{}'.
this.edgeLength = options.edgeLength || 3
// @ts-expect-error ts-migrate(2339) FIXME: Property 'newline' does not exist on type '{}'.
this.newline = options.newline || '\n '
// @ts-expect-error ts-migrate(2339) FIXME: Property 'startNumber' does not exist on type '{}'... Remove this comment to see the full error message
const start = options.startNumber || 1
if (typeof this.scale === 'number') {
this.scaleKey = false
this.scale = Array(this.scale)
.fill(0)
.map((v, i) => ({ name: i + start }))
}
// @ts-expect-error ts-migrate(2339) FIXME: Property 'executionGroups' does not exist on type ... Remove this comment to see the full error message
options.executionGroups.forEach((executionGroup: ExecutionGroup, index: number) => {
this.choices.unshift({
...executionGroup,
name: executionGroup.name,
scriptExecutable: executionGroup.scriptExecutable,
scriptCommand: executionGroup.scriptCommand,
initial:
executionGroup.initial !== undefined && !Array.isArray(executionGroup.initial)
? [executionGroup.initial]
: executionGroup.initial,
category: executionGroup.category,
allowMultipleScripts: executionGroup.allowMultipleScripts,
scriptNames: executionGroup.scriptNames,
executionGroupIndex: index,
availableScripts: executionGroup.scriptNames
})
this.scale = [
...this.scale,
...executionGroup.scriptNames.map((name: string) => ({
name,
executionGroupIndex: index
}))
]
})
this.choices.forEach((choice: ChoiceInPrompt) => {
// selected scale indexes
choice.selected = choice.selected || []
// ensure _some_ category exists
choice.category = choice.category || this.options.uncategorizedText
// add "ignore" to availableScripts, if missing
// @ts-expect-error ts-migrate(2339) FIXME: Property 'ignoreText' does not exist on type '{}'.
choice.availableScripts = [options.ignoreText].concat(
// @ts-expect-error ts-migrate(2339) FIXME: Property 'ignoreText' does not exist on type '{}'.
choice.availableScripts.filter((script: string) => script !== options.ignoreText)
)
})
this.choices = this.getSortedChoices(this.choices)
// for padding
this.longestPackageNameLength = this.choices.reduce((longest: number, curr: ChoiceInPrompt) => {
const result = curr.name.length + 4
return result > longest ? result : longest
}, 0)
// for padding
this.shortestPackageNameLength = this.choices.reduce(
(shortest: number, curr: ChoiceInPrompt) => {
const result = curr.name.length
return result < shortest ? result : shortest
},
this.longestPackageNameLength
)
// for padding, although not really used atm
this.longestScaleItemNameLength = Math.min(
this.choices.reduce((longest: number, currentChoice: ChoiceInPrompt) => {
const longestInsideChoice = currentChoice.availableScripts.reduce(
(longestInsideChoiceSoFar: number, currentScaleItem: string) => {
return currentScaleItem.length > longestInsideChoiceSoFar
? currentScaleItem.length
: longestInsideChoiceSoFar
},
0
)
return longestInsideChoice > longest ? longestInsideChoice : longest
}, 0),
15
)
this.filterText = ''
const resizeHandler = () => {
this.render()
}
this.stdout.on('resize', resizeHandler)
this.on('close', () => {
this.stdout.removeListener('resize', resizeHandler)
})
}
getSortedChoices(choices: Array<ChoiceInPrompt>): Array<ChoiceInPrompt> {
return choices.sort((a: ChoiceInPrompt, b: ChoiceInPrompt) => {
const customSortOrder = (input: string) => {
switch (input) {
case this.uncategorizedText:
return '`'
default:
return input
}
}
return customSortOrder(a.customSortText || a.category) <
customSortOrder(b.customSortText || b.category)
? -1
: 1
})
}
applyFilter(): void {
if (this.filterText !== '') {
this.visible = this.getFilteredChoices(this.filterText, this.choices)
} else {
// back to no filtering, restore the view
this.state.visible = undefined
}
}
delete(): void {
if (this.filterText.length > 0) {
this.filterText = this.filterText.substring(0, this.filterText.length - 1)
this.applyFilter()
this.index = 0
this.render()
}
}
number(n: string, key: KeyPressEvent): void {
this.onKeyPress(n, key)
}
onKeyPress(ch: string, key: KeyPressEvent): void {
const noFilterPreviouslyApplied = this.filterText === ''
if (
typeof ch === 'string' &&
key.raw === key.sequence &&
!key.ctrl &&
!key.meta &&
!key.option
) {
// it's a typable character, and it's not a special character like a \n
this.filterText += ch.toLowerCase()
} else {
// no filter-related key presses, return early
return
}
if (this.filterText !== '' || (this.filterText === '' && !noFilterPreviouslyApplied)) {
this.applyFilter()
}
this.index = 0
this.render()
}
async reset(): Promise<void> {
this.tableized = false
await super.reset()
return this.render()
}
tableize(): void {
if (this.tableized === true) return
this.tableized = true
let longest = 0
for (const ch of this.choices) {
longest = Math.max(longest, ch.message.length)
if (Array.isArray(ch.initial)) {
const selectedIndexes = ch.initial
.map((item: string) => this.scale.findIndex((s: ScaleWithName) => s.name === item))
.filter((selectedIndex: number) => selectedIndex !== -1)
if (selectedIndexes.length > 1) {
ch.scaleIndex = ch.selected[0]
ch.selected = selectedIndexes
} else if (selectedIndexes.length === 1) {
// it's just one item, let's not lock the selection, requiring a space keypress.
ch.scaleIndex = selectedIndexes[0]
}
} else {
ch.scaleIndex = 0
}
// // increase initial by 1, since we added "ignore"
// if (Array.isArray(choice.initial)) {
// choice.initial = choice.initial.map((item: number) => item + 1)
// }
ch.scale = []
for (let i = 0; i < this.scale.length; i++) {
ch.scale.push({ index: i })
}
}
this.widths[0] = Math.min(this.widths[0], longest + 3)
}
async space(): Promise<void> {
if (this.selected.allowMultipleScripts !== false) {
this.toggleSelectionForScaleIndexInChoice(this.selected)
}
}
toggleSelectionForScaleIndexInChoice(choice: ChoiceInPrompt): void {
if (this.getChoiceAvailableScriptIndexes(choice)[0].index === choice.scaleIndex) {
// it's just an ignore scale item, don't select it
return
}
const index = choice.selected.indexOf(choice.scaleIndex)
if (index !== -1) {
choice.selected.splice(index, 1)
} else {
choice.selected.push(choice.scaleIndex)
}
this.render()
}
async dispatch(s: string, key: KeyPressEvent): Promise<void> {
if (this.multiple) {
// not sure what multiple is, was here when I got here!
return this[key.name] ? await this[key.name](s, key) : await super.dispatch(s, key)
} else {
this.onKeyPress(s, key)
}
}
separator(): string {
return this.styles.muted(this.symbols.ellipsis)
}
getReindexedChoices(choices: Array<ChoiceInPrompt>): Array<ChoiceInPrompt> {
const result = [...choices]
result.forEach((ch: ChoiceInPrompt, index: number) => (ch.index = index))
return result
}
isValidScaleItem(scaleItemName: ScaleWithName, choice: ChoiceInPrompt): boolean {
return (
scaleItemName === this.options.ignoreText || this.isScriptAvailable(scaleItemName, choice)
)
}
getNextIndexThatHasAvailableScript(direction: 'left' | 'right', choice: ChoiceInPrompt): number {
let nextIndex = choice.scaleIndex + (direction === 'right' ? 1 : -1)
const isIndexWithinBounds = (i: number) => i >= 0 && i < this.scale.length
while (
isIndexWithinBounds(nextIndex) &&
!this.isValidScaleItem(this.scale[nextIndex], choice)
) {
nextIndex += direction === 'right' ? 1 : -1
}
if (isIndexWithinBounds(nextIndex)) {
return nextIndex
}
throw new Error('no scale script item available to move to in that direction')
}
right(): Promise<void> {
const choice = this.visible[this.index]
if (choice.scaleIndex >= this.scale.length - 1) return this.alert()
try {
choice.scaleIndex = this.getNextIndexThatHasAvailableScript('right', choice)
} catch (e) {
if (e.message !== 'no scale script item available to move to in that direction') {
throw e
}
}
return this.render()
}
left(): Promise<void> {
const choice = this.visible[this.index]
if (choice.scaleIndex <= 0) return this.alert()
try {
choice.scaleIndex = this.getNextIndexThatHasAvailableScript('left', choice)
return this.render()
} catch (e) {
if (e.message !== 'no scale script item available to move to in that direction') {
throw e
}
}
return this.render()
}
indent(): string {
return ''
}
format(): string {
if (this.state.submitted) {
const values = this.choices.map((ch: ChoiceInPrompt) => this.styles.info(ch.index))
return values.join(', ')
}
return ''
}
pointer(): string {
return ''
}
/**
* Render the scale "Key". Something like:
* @return {String}
*/
renderScaleKey(): string {
if (this.scaleKey === false) return ''
if (this.state.submitted) return ''
const scale = this.scale.map((item: ScaleWithName) => ` ${item.name} - ${item.message}`)
const key = ['', ...scale].map((item) => this.styles.muted(item))
return key.join('\n')
}
isScriptAvailable(scaleItem: ScaleWithName, choice: ChoiceInPrompt): boolean {
return (
scaleItem.executionGroupIndex === choice.executionGroupIndex &&
choice.availableScripts.includes(scaleItem.name)
)
}
/**
* Render a scale indicator => ignore ── build ── build:prod
*/
scaleIndicator(choice: ChoiceInPrompt, item: ScaleWithIndex, choiceIndex: number): string {
const scaleItem = this.scale[item.index]
const scaleItemIsUnderCursor = choice.scaleIndex === item.index
const scaleItemIsSelected = choice.selected.includes(item.index)
const isIgnoreScript =
this.getChoiceAvailableScriptIndexes(choice)[0].index === choice.scaleIndex
const choiceIsFocused = this.index === choiceIndex
if (!this.isScriptAvailable(scaleItem, choice)) {
return ''
} else if (choiceIsFocused && scaleItemIsUnderCursor && scaleItemIsSelected) {
return this.styles.strong(this.styles.cyan(' =' + scaleItem.name + '= '))
} else if (choiceIsFocused && scaleItemIsUnderCursor && !scaleItemIsSelected) {
return this.styles.strong(this.styles.danger(' [' + scaleItem.name + '] '))
} else if (!choiceIsFocused && scaleItemIsUnderCursor && scaleItemIsSelected) {
return this.styles.success(' =' + this.styles.underline(scaleItem.name) + '= ')
} else if (isIgnoreScript) {
return this.styles.default(' ' + scaleItem.name + ' ')
} else if (!choiceIsFocused && scaleItemIsUnderCursor && !scaleItemIsSelected) {
return this.styles.success(' -' + scaleItem.name + '- ')
} else if (!choiceIsFocused && !scaleItemIsUnderCursor && scaleItemIsSelected) {
return this.styles.success(' =' + scaleItem.name + '= ')
} else if (choiceIsFocused && !scaleItemIsUnderCursor && scaleItemIsSelected) {
return this.styles.success(' =' + scaleItem.name + '= ')
} else if (choiceIsFocused) {
return this.styles.danger(' ' + scaleItem.name + ' ')
}
return this.styles.default(' ' + scaleItem.name + ' ')
}
getChoiceSelectedScriptIndex(choice: ChoiceInPrompt): number {
return this.getChoiceAvailableScriptIndexes(choice).findIndex(
(item: ScaleWithIndex) => item.index === choice.scaleIndex
)
}
getChoiceAvailableScriptIndexes(choice: ChoiceInPrompt): Array<ScaleWithIndex> {
return choice.scale.filter((s: ScaleWithIndex) =>
this.isScriptAvailable(this.scale[s.index], choice)
)
}
/**
* Render the actual scale => ◯────◯────◉────◯────◯
*/
renderScale(choice: ChoiceInPrompt, i: number, maxScaleItemsOnScreen: number): string {
let scaleItems = choice.scale
.map((item: ScaleWithIndex) => this.scaleIndicator(choice, item, i))
.filter((i: string) => i !== '')
const choiceScaleIndex = this.getChoiceSelectedScriptIndex(choice)
let scrollsFromLeftEdge = null
let scrollsFromRightEdge = null
if (scaleItems.length > maxScaleItemsOnScreen) {
const scrollingIndex =
choiceScaleIndex -
(choiceScaleIndex % maxScaleItemsOnScreen) +
// account for end of right side not being a multiplier of max items count
Math.max(0, choiceScaleIndex + maxScaleItemsOnScreen - scaleItems.length)
const sliceStart =
scrollingIndex + maxScaleItemsOnScreen < scaleItems.length
? scrollingIndex
: scaleItems.length - maxScaleItemsOnScreen
const sliceEnd = Math.min(scaleItems.length, sliceStart + maxScaleItemsOnScreen)
scrollsFromLeftEdge = Math.ceil(sliceStart / maxScaleItemsOnScreen)
scrollsFromRightEdge = Math.ceil((scaleItems.length - sliceEnd) / maxScaleItemsOnScreen)
scaleItems = scaleItems.slice(sliceStart, sliceStart + maxScaleItemsOnScreen)
}
scaleItems = scaleItems.filter((scaleItem: string) => scaleItem)
const padding = this.term === 'Hyper' ? '' : ''
return (
// @ts-expect-error ts-migrate(2531) FIXME: Object is possibly 'null'.
(scrollsFromLeftEdge > 0
? '[' +
new Array(scrollsFromLeftEdge)
.fill(1)
.map(() => '.')
.join('') +
']' +
padding
: '') +
scaleItems.join(padding + this.symbols.line.repeat(this.edgeLength) + padding) +
// @ts-expect-error ts-migrate(2531) FIXME: Object is possibly 'null'.
(scrollsFromRightEdge > 0
? padding +
'[' +
new Array(scrollsFromRightEdge)
.fill(1)
.map(() => '.')
.join('') +
']'
: '')
)
}
get limit(): number {
const { state, options, choices } = this
const limit = state.limit || this._limit || options.limit || choices.length
const categories = this.choices.reduce((categories: Set<string>, val: ChoiceInPrompt) => {
categories.add(val.category)
return categories
}, new Set())
return Math.min(limit, this.height - categories.size)
}
/**
* Render a choice, including scale =>
* "The website is easy to navigate. ◯───◯───◉───◯───◯"
*/
async renderChoice(
choice: ChoiceInPrompt,
i: number,
bulletIndentation = false
): Promise<Array<string>> {
await this.onChoice(choice, i)
const focused = this.index === i
// @ts-expect-error ts-migrate(2554) FIXME: Expected 0 arguments, but got 2.
const pointer = await this.pointer(choice, i)
let hint = await choice.hint
if (hint && !utils.hasColor(hint)) {
hint = this.styles.muted(hint)
}
let maxScaleItemsOnScreen = 20
const pad = (str: string) =>
this.margin[3] + str.replace(/\s+$/, '').padEnd(this.widths[0], ' ')
const newline = this.newline
const ind = this.indent()
const message = await this.resolve(choice.message, this.state, choice, i)
let scale = await this.renderScale(choice, i, maxScaleItemsOnScreen)
const margin = this.margin[1] + this.margin[3]
this.scaleLength = colors.unstyle(scale).length
this.widths[0] = Math.min(
this.widths[0],
this.longestPackageNameLength + margin - this.shortestPackageNameLength
)
const msg = utils.wordWrap(message, { width: this.widths[0], newline })
let lines = msg.split('\n').map((line: string) => pad(line) + this.margin[1])
let selectedBulletCharacter = '─'
let bulletCharacter = ' '
const now = new Date()
if (now.getMonth() == 10 && now.getDate() == 31) {
selectedBulletCharacter = '😱'
bulletCharacter = '👻'
}
const hasSiblingAbove = this.visible[i - 1] && this.visible[i - 1].name === choice.name
const hasSiblingBelow = this.visible[i + 1] && this.visible[i + 1].name === choice.name
const hasSiblingsInBothDirections = hasSiblingAbove && hasSiblingBelow
let suffixSymbol = ' '
if (hasSiblingsInBothDirections) {
lines[0] = padReplace(lines[0])
suffixSymbol = '│'
} else if (hasSiblingAbove) {
suffixSymbol = '└'
lines[0] = padReplace(lines[0])
} else if (hasSiblingBelow) {
suffixSymbol = '┌'
}
if (focused) {
lines = lines.map((line: string) =>
this.styles.hasAnsi(line) ? line : this.styles.danger(line)
)
lines[0] = bulletIndentation ? selectedBulletCharacter + '─> ' + lines[0] : '> '
} else {
lines[0] = bulletIndentation ? bulletCharacter + ' ' + lines[0] : lines[0]
}
lines[0] += suffixSymbol
if (this.linebreak) lines.push('')
let renderedChoice
let columnSpaceRemaining
const termColumns = process.stdout.columns
do {
scale = await this.renderScale(choice, i, maxScaleItemsOnScreen)
const terminalFittedLines = [...lines]
terminalFittedLines[0] += this.focused ? this.styles.info(scale) : scale
renderedChoice = [ind + pointer, terminalFittedLines.join('\n')].filter(Boolean)
columnSpaceRemaining =
termColumns -
stripAnsi(Array.isArray(renderedChoice) ? renderedChoice[0] : renderedChoice).length
maxScaleItemsOnScreen--
} while (columnSpaceRemaining < 25 && maxScaleItemsOnScreen > 0)
return renderedChoice
}
isChoiceCategorized(choice: ChoiceInPrompt): boolean {
return choice.category !== this.options.uncategorizedText
}
areAllChoicesUncategorized(choices: Array<ChoiceInPrompt>): boolean {
return choices.every((ch: ChoiceInPrompt) => ch.category === this.options.uncategorizedText)
}
async renderChoicesAndCategories(): Promise<string | Array<string>> {
if (this.state.submitted) return ''
this.tableize()
// fix the indexing?
this.visible.forEach((ch: ChoiceInPrompt, index: number) => (ch.index = index))
const categorizedChoicesExist = this.visible.some((ch: ChoiceInPrompt) =>
this.isChoiceCategorized(ch)
)
const choicesAndCategories = []
for (let i = 0; i < this.visible.length; i++) {
const ch = this.visible[i]
const renderedChoice = await this.renderChoice(ch, i, true)
if (categorizedChoicesExist || this.filterText !== '') {
const prevChoiceCategory = i === 0 ? null : this.visible[i - 1].category
if (prevChoiceCategory !== ch.category) {
choicesAndCategories.push(this.styles.underline(ch.category))
}
}
choicesAndCategories.push(renderedChoice)
}
const visible = (await Promise.all(choicesAndCategories)).flat()
return this.margin[0] + visible.join('\n')
}
async getFilterHeading(): Promise<string> {
if (this.filterText !== '') {
return 'Filtering by: ' + this.filterText + '\n'
}
return '[Type/backspace to filter, lead with ! to filter selected projects. Use up/down to change project, left/right to switch scripts to run. Space to select multiple project scripts]\n'
}
getFilteredChoices(
filterText: string,
choices: Array<ChoiceInPrompt> /*, defaultItem*/
): Array<ChoiceInPrompt> {
let choicesToFilter = choices
if (filterText.startsWith('!')) {
choicesToFilter = choices.filter((choice) => this.getChoiceSelectedScriptIndex(choice) > 0)
filterText = filterText.slice(1)
}
return this.getSortedChoices(
fuzzy
.filter(filterText || '', choicesToFilter, {
// fuzzy options
// pre: ansiStyles.green.open,
// post: ansiStyles.green.close,
extract: (choice: ChoiceInPrompt) => choice.ansiLessName || stripAnsi(choice.name)
})
.map((e: { string: string; original: ChoiceInPrompt }) => {
e.original.ansiLessName = stripAnsi(e.string)
e.original.name = e.string
e.original.message = e.string
return e.original
})
)
}
async render(): Promise<void> {
const { submitted, size } = this.state
const prefix = await this.prefix()
const separator = await this.separator()
const message = await this.message()
let prompt = ''
if (this.options.promptLine !== false) {
prompt = [prefix, message, separator, ''].join(' ')
this.state.prompt = prompt
}
this.visible.forEach((ch: ChoiceInPrompt) => {
if (ch.scaleIndex === undefined) {
ch.scaleIndex = 1
}
})
const header = await this.header()
const output = await this.format()
// let key = await this.renderScaleKey()
const help = (await this.error()) || (await this.hint())
const body = await this.renderChoicesAndCategories()
const footer = await this.footer()
const err = this.emptyError
if (output) prompt += output
if (help && !prompt.includes(help)) prompt += ' ' + help
if (submitted && !output && !(body as string).trim() && this.multiple && err != null) {
prompt += this.styles.danger(err)
}
const filterHeading = await this.getFilterHeading()
this.clear(size)
this.write([header, prompt /*, key*/, filterHeading, body, footer].filter(Boolean).join('\n'))
if (!this.state.submitted) {
this.write(this.margin[2])
}
this.restore()
}
async submit(): Promise<void> {
this.value = []
for (const choice of this.choices) {
const availableScriptIndexes = this.getChoiceAvailableScriptIndexes(choice)
if (
!choice.selected.includes(choice.scaleIndex) &&
choice.scaleIndex !== availableScriptIndexes[0].index
) {
// a script is focused which is not the ignore script
choice.selected.push(choice.scaleIndex)
}
this.getChoiceAvailableScriptIndexes(choice)[0].index
const selectedScripts: Array<string> = availableScriptIndexes
.filter(({ index }) => choice.selected.includes(index))
.map(({ index }) => this.scale[index].name)
for (const script of selectedScripts) {
if (script !== undefined) {
this.value.push({
packageName: choice.name,
script,
scriptExecutable: choice.scriptExecutable,
scriptCommand: choice.scriptCommand
})
}
}
}
return this.base.submit.call(this)
}
}
export default RushSelect