实现说明
hotkeys 定义在模块顶层,中间不经过函数作用域。
使用要点
- 浏览器才是这里的运行环境:
document在 Node 里拿不到。 - 守卫
tag === 'INPUT' || tag === 'TEXTAREA' || event.isComposing一旦成立就走提前的return,把后续流程挡掉。 - 直接运行文件,输出会带上标签,比如
action: save、action: command palette、action: help overlay——输出的每一行都能指回产生它的那次调用。
常见问题
「键盘快捷键映射表」能在裸 Node.js 里跑吗?
不能——document 这些 API 由浏览器提供,Node 进程里拿不到。要执行的话,请在页面里(或 DevTools 控制台)运行。
核心语句
const tag = event.target?.tagName;
代码示例
// Hotkey map: keydown combinations become actions; modifier keys are part
// of the combination so Ctrl+S never triggers the plain S handler
const hotkeys = {
'mod+s': () => console.log('action: save'),
'mod+shift+p': () => console.log('action: command palette'),
'?': () => console.log('action: help overlay'),
};
document.addEventListener('keydown', (event) => {
const tag = event.target?.tagName;
if (tag === 'INPUT' || tag === 'TEXTAREA' || event.isComposing) return;
const key = event.key.toLowerCase();
const isLetter = key.length === 1 && key >= 'a' && key <= 'z';
const combo = [];
if (event.ctrlKey || event.metaKey) combo.push('mod');
if (event.altKey) combo.push('alt');
// shift is only a modifier for letters: on most layouts the '?' key
// already carries the shift inside the key itself
if (event.shiftKey && isLetter) combo.push('shift');
combo.push(key);
const handler = hotkeys[combo.join('+')];
if (handler) {
event.preventDefault();
handler();
}
});
console.log('registered hotkeys:', Object.keys(hotkeys).join(', '));