50 lines
1.4 KiB
TypeScript
50 lines
1.4 KiB
TypeScript
export const useKeyboardShortcuts = () => {
|
|
const shortcutsMap = new Map<string, () => void>();
|
|
|
|
const normalize = (combo: string[]) =>
|
|
combo.map(k => k.toLowerCase()).sort().join('+');
|
|
|
|
const addShortcut = (combo: string[], callback: () => void) => {
|
|
const normalizedKey = normalize(combo);
|
|
shortcutsMap.set(normalizedKey, callback);
|
|
|
|
return () => {
|
|
shortcutsMap.delete(normalizedKey);
|
|
};
|
|
};
|
|
|
|
const handleKeyDown = (event: KeyboardEvent) => {
|
|
const keys: string[] = [];
|
|
if (event.ctrlKey) keys.push('ctrl');
|
|
if (event.metaKey) keys.push('meta');
|
|
if (event.shiftKey) keys.push('shift');
|
|
if (event.altKey) keys.push('alt');
|
|
|
|
const mainKey = event.key.toLowerCase();
|
|
if (!['control', 'shift', 'meta', 'alt'].includes(mainKey)) {
|
|
keys.push(mainKey);
|
|
}
|
|
|
|
const pressedCombo = normalize(keys);
|
|
|
|
if (shortcutsMap.has(pressedCombo)) {
|
|
event.preventDefault();
|
|
event.stopPropagation();
|
|
shortcutsMap.get(pressedCombo)!();
|
|
}
|
|
};
|
|
|
|
onMounted(() => {
|
|
document.addEventListener('keydown', handleKeyDown);
|
|
});
|
|
|
|
onUnmounted(() => {
|
|
document.removeEventListener('keydown', handleKeyDown);
|
|
});
|
|
|
|
return {
|
|
addShortcut,
|
|
handleKeyDown,
|
|
};
|
|
};
|