salix/front/core/directives/bind.js

61 lines
1.7 KiB
JavaScript
Raw Normal View History

import ngModule from '../module';
directive.$inject = ['$document'];
export function directive($document) {
let modifiers = ["alt", "ctrl", "meta", "shift"];
function checkAttributes($attrs) {
let shortcut = $attrs.vnBind.split(' ');
let keys = {};
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) {
correctShortcut = correctShortcut && shortcut[key] == event[key];
}
if (correctShortcut) {
event.preventDefault();
$element.triggerHandler('click');
}
}
$document.on("keyup", onKeyUp);
$element.on('$destroy', function() {
$document.off('keyup', onKeyUp);
});
}
};
}
ngModule.directive('vnBind', directive);