feat: keyShortcut directive

This commit is contained in:
Javier Segarra 2024-08-28 14:04:48 +02:00
parent 8619abdfb4
commit 72388af418
2 changed files with 34 additions and 0 deletions

32
src/boot/keyShortcut.js Normal file
View File

@ -0,0 +1,32 @@
export default {
mounted: function (el, binding) {
const shortcut = binding.value ?? '+';
const { key, ctrl, alt, callback } =
typeof shortcut === 'string'
? {
key: shortcut,
ctrl: true,
alt: true,
callback: () =>
document.querySelector('button[shortcut="+"]')?.click(),
}
: binding.value;
const handleKeydown = (event) => {
if (event.key === key && (!ctrl || event.ctrlKey) && (!alt || event.altKey)) {
callback();
}
};
// Attach the event listener to the window
window.addEventListener('keydown', handleKeydown);
el._handleKeydown = handleKeydown;
},
unmounted: function (el) {
if (el._handleKeydown) {
window.removeEventListener('keydown', el._handleKeydown);
}
},
};

View File

@ -1,6 +1,8 @@
import { boot } from 'quasar/wrappers';
import qFormMixin from './qformMixin';
import keyShortcut from './keyShortcut';
export default boot(({ app }) => {
app.mixin(qFormMixin);
app.directive('shortcut', keyShortcut);
});