Files
yinx-cli/lib/keyboard.js
2025-12-22 12:07:12 +08:00

51 lines
1.1 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import readline from "readline";
let initialized = false;
let currentHandler = null;
function ensureRawMode(enabled) {
if (process.stdin.isTTY) {
process.stdin.setRawMode(enabled);
}
}
export function initKeypress() {
// 清理所有keypress监听器
process.stdin.removeAllListeners("keypress");
currentHandler = null;
// 初始化readline只需一次
if (!initialized) {
readline.emitKeypressEvents(process.stdin);
initialized = true;
}
ensureRawMode(true);
}
export function onKey(handler) {
// 清理旧的监听器
process.stdin.removeAllListeners("keypress");
currentHandler = handler;
process.stdin.on("keypress", handler);
}
export function stopKeypress() {
process.stdin.removeAllListeners("keypress");
currentHandler = null;
ensureRawMode(false);
}
export function waitForKey(message = "按任意键返回...", predicate = () => true) {
return new Promise(resolve => {
console.log("\n" + message);
initKeypress();
onKey((str, key) => {
const pressed = key || {};
if (!predicate(pressed)) return;
stopKeypress();
resolve(pressed);
});
});
}