salix/front/core/directives/bind.js

61 lines
1.7 KiB
JavaScript
Raw Permalink Normal View History

import ngModule from '../module';
directive.$inject = ['$document'];
export function directive($document) {
2019-10-24 08:17:32 +00:00
let modifiers = ['alt', 'ctrl', 'meta', 'shift'];
function checkAttributes($attrs) {
let shortcut = $attrs.vnBind.split(' ');
let keys = {};
2019-10-24 08:17:32 +00:00
if (shortcut[0] == '')
throw new Error('vnBind: Binding keys not defined');
if (shortcut.length == 1) {
keys.altKey = true;
keys.ctrlKey = true;
} else {
let mods = shortcut.splice(0, shortcut.length - 1);
for (let mod of mods) {
if (modifiers.indexOf(mod) == -1)
throw new Error('vnBind: Invalid modifier key in binding');
keys[`${mod}Key`] = true;
}
}
keys.key = shortcut[0];
if (keys.key == 'space') keys.key = ' ';
return keys;
}
return {
restrict: 'A',
link: function($scope, $element, $attrs) {
let shortcut = checkAttributes($attrs);
function onKeyUp(event) {
if (event.defaultPrevented) return;
let correctShortcut = true;
for (const key in shortcut) {
2019-10-24 08:17:32 +00:00
correctShortcut = correctShortcut
&& shortcut[key] == event[key];
}
if (correctShortcut) {
event.preventDefault();
$element.triggerHandler('click');
}
}
2019-10-24 08:17:32 +00:00
$document.on('keyup', onKeyUp);
$element.on('$destroy', function() {
$document.off('keyup', onKeyUp);
});
}
};
}
ngModule.directive('vnBind', directive);