Skip to content

Commit 35f0cb8

Browse files
committed
add prompt manager
1 parent d3c442e commit 35f0cb8

File tree

2 files changed

+251
-208
lines changed

2 files changed

+251
-208
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import { prompt } from 'gluegun';
2+
import { PromptOptions } from 'gluegun/build/types/toolbox/prompt-enquirer-types';
3+
4+
interface PromptStep {
5+
execute: () => Promise<any>;
6+
}
7+
8+
export class PromptManager {
9+
private steps: PromptStep[] = [];
10+
private currentStep = 0;
11+
private results: any[] = [];
12+
13+
addStep(options: PromptOptions) {
14+
this.steps.push({
15+
execute: async () => {
16+
const result = await prompt.ask(options);
17+
return result;
18+
},
19+
});
20+
}
21+
22+
async executePrompts() {
23+
let isCtrlC = false;
24+
// gluegun always throws empty string, so we have this workaround
25+
const keypressHandler = (_: string, key: { name: string; ctrl: boolean }) => {
26+
if (key.ctrl && key.name === 'c') {
27+
isCtrlC = true;
28+
}
29+
};
30+
process.stdin.on('keypress', keypressHandler);
31+
32+
while (this.currentStep < this.steps.length) {
33+
try {
34+
const result = await this.steps[this.currentStep].execute();
35+
this.results[this.currentStep] = result;
36+
this.currentStep++;
37+
} catch (error) {
38+
if (error instanceof Error) {
39+
throw error;
40+
}
41+
if (isCtrlC || this.currentStep === 0) {
42+
process.stdout.write('\n');
43+
process.exit(0);
44+
}
45+
// delete 2 lines
46+
process.stdout.write('\x1b[1A\x1b[2K\x1b[1A\x1b[2K');
47+
this.currentStep--;
48+
}
49+
}
50+
51+
process.stdin.removeListener('keypress', keypressHandler);
52+
return this.results;
53+
}
54+
}

0 commit comments

Comments
 (0)