salix-front/src/boot/keyShortcut.js

34 lines
948 B
JavaScript

export default {
mounted(el, binding) {
const shortcut = binding.value || '+';
const { key, ctrl, alt, callback } =
typeof shortcut === 'string'
? {
key: shortcut,
ctrl: true,
alt: true,
callback: () => el?.click(),
}
: binding.value;
if (!el.hasAttribute('shortcut')) {
el.setAttribute('shortcut', key);
}
const handleKeydown = (event) => {
if (event.key === key && (!ctrl || event.ctrlKey) && (!alt || event.altKey)) {
callback();
}
};
window.addEventListener('keydown', handleKeydown);
el._handleKeydown = handleKeydown;
},
unmounted(el) {
if (el._handleKeydown) {
window.removeEventListener('keydown', el._handleKeydown);
}
},
};