Update.
This commit is contained in:
@@ -0,0 +1,55 @@
|
||||
class KeyboardShortcuts {
|
||||
constructor() {
|
||||
this.shortcuts = new Map();
|
||||
this.enabled = true;
|
||||
this.init();
|
||||
}
|
||||
|
||||
init() {
|
||||
document.addEventListener('keydown', (e) => {
|
||||
if (!this.enabled) return;
|
||||
|
||||
const isInput = ['INPUT', 'TEXTAREA'].includes(e.target.tagName);
|
||||
const key = this.getKeyCombo(e);
|
||||
|
||||
if (this.shortcuts.has(key)) {
|
||||
const { handler, allowInInput } = this.shortcuts.get(key);
|
||||
if (!isInput || allowInInput) {
|
||||
e.preventDefault();
|
||||
handler(e);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
getKeyCombo(e) {
|
||||
const parts = [];
|
||||
if (e.ctrlKey || e.metaKey) parts.push('ctrl');
|
||||
if (e.altKey) parts.push('alt');
|
||||
if (e.shiftKey) parts.push('shift');
|
||||
parts.push(e.key.toLowerCase());
|
||||
return parts.join('+');
|
||||
}
|
||||
|
||||
register(keyCombo, handler, allowInInput = false) {
|
||||
this.shortcuts.set(keyCombo.toLowerCase(), { handler, allowInInput });
|
||||
}
|
||||
|
||||
unregister(keyCombo) {
|
||||
this.shortcuts.delete(keyCombo.toLowerCase());
|
||||
}
|
||||
|
||||
enable() {
|
||||
this.enabled = true;
|
||||
}
|
||||
|
||||
disable() {
|
||||
this.enabled = false;
|
||||
}
|
||||
|
||||
getRegisteredShortcuts() {
|
||||
return Array.from(this.shortcuts.keys());
|
||||
}
|
||||
}
|
||||
|
||||
export const shortcuts = new KeyboardShortcuts();
|
||||
Reference in New Issue
Block a user