Skip to content

Commit 93526fb

Browse files
committed
Refactor TerminalKeypress to improve keypress handling
- Introduced a dataHandler to manage keypress events more cleanly. - Delayed setting raw mode until resume() is called, ensuring proper input handling. - Updated destroy method to safely remove the data listener and reset dataHandler.
1 parent dee8025 commit 93526fb

File tree

1 file changed

+12
-6
lines changed

1 file changed

+12
-6
lines changed

packages/inquirerer/src/keypress.ts

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ export class TerminalKeypress {
2828
private noTty: boolean;
2929
private input: Readable;
3030
private proc: ProcessWrapper;
31+
private dataHandler: ((key: string) => void) | null = null;
3132

3233
constructor(
3334
noTty: boolean = false,
@@ -38,10 +39,8 @@ export class TerminalKeypress {
3839
this.input = input;
3940
this.proc = proc;
4041

42+
// Don't set raw mode yet; let resume() handle it when necessary
4143
if (this.isTTY()) {
42-
if (typeof (this.input as any).setRawMode === 'function') {
43-
(this.input as any).setRawMode(true);
44-
}
4544
this.input.resume();
4645
this.input.setEncoding('utf8');
4746
}
@@ -53,14 +52,15 @@ export class TerminalKeypress {
5352
}
5453

5554
private setupListeners(): void {
56-
this.input.on('data', (key: string) => {
55+
this.dataHandler = (key: string) => {
5756
if (!this.active) return;
5857
const handlers = this.listeners[key];
5958
handlers?.forEach(handler => handler());
6059
if (key === KEY_CODES.CTRL_C) { // Ctrl+C
6160
this.proc.exit(0);
6261
}
63-
});
62+
};
63+
this.input.on('data', this.dataHandler);
6464
}
6565

6666
on(key: string, callback: KeyHandler): void {
@@ -89,13 +89,19 @@ export class TerminalKeypress {
8989

9090
resume(): void {
9191
this.active = true;
92+
if (this.isTTY() && typeof (this.input as any).setRawMode === 'function') {
93+
(this.input as any).setRawMode(true);
94+
}
9295
}
9396

9497
destroy(): void {
9598
if (typeof (this.input as any).setRawMode === 'function') {
9699
(this.input as any).setRawMode(false);
97100
}
98101
this.input.pause();
99-
this.input.removeAllListeners('data');
102+
if (this.dataHandler) {
103+
this.input.removeListener('data', this.dataHandler);
104+
this.dataHandler = null;
105+
}
100106
}
101107
}

0 commit comments

Comments
 (0)