Files
yinx-cli/lib/keyboard.js
2026-01-15 10:24:02 +08:00

57 lines
1.3 KiB
JavaScript
Raw Permalink 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;
// 确保raw mode关闭再重新开启
ensureRawMode(false);
// 初始化readline只需一次
if (!initialized) {
readline.emitKeypressEvents(process.stdin);
initialized = true;
}
// 短暂延迟后再开启raw mode
setImmediate(() => {
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);
});
});
}