-
Notifications
You must be signed in to change notification settings - Fork 0
/
mousetrap.js
99 lines (74 loc) · 2.56 KB
/
mousetrap.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
'use strict';
/**
* Mousetrap directives for angularJS
*
* @author Javis Pérez <javisperez@gmail.com> <http://www.javisperez.com>
* 03-16-2016
*/
angular.module('mousetrap-directives', [])
// Generic mousetrap factory
.factory('$mousetrap', function ($window, $route, $rootScope, $uibModal, $timeout) {
var isMac = $window.navigator.platform.toLowerCase().indexOf('mac') > -1;
function parseModKey(key) {
if (isMac) {
return key.replace(/(mod)/ig, 'command');
}
return key.replace(/(mod)/ig, 'ctrl');
}
return function (hotkeys, $element, attrs) {
var keys = Object.keys(hotkeys);
keys.forEach(function (key) {
var fn = hotkeys[key];
Mousetrap.bind(key, function (ev, combo) {
ev.preventDefault();
if ($element.is(':disabled')) {
return false;
}
fn(ev, combo);
return false;
});
});
};
})
/**
* mousetrap directive to execute the given action with a keyboard shortcut
*/
.directive('mousetrap', function ($timeout, $mousetrap) {
return {
restrict: 'A',
link: function ($scope, $element, attrs) {
var evald = $scope.$eval(attrs.mousetrap);
$timeout(function () {
if (!angular.isObject(evald) && typeof evald === 'string') {
var tmp = {};
tmp[evald] = function () {
$element[0].click();
};
evald = tmp;
}
$mousetrap(evald, $element, attrs);
});
}
};
})
/**
* Set the focus to a given field by using a custom keyboard shortcut
*/
.directive('mousetrapFocus', function ($timeout, $mousetrap) {
return {
restrict: 'A',
link: function ($scope, $element, attrs) {
var evald = $scope.$eval(attrs.mousetrapFocus);
$timeout(function () {
if (typeof evald !== 'string') {
return;
}
var tmp = {};
tmp[evald] = function () {
$element.focus();
};
$mousetrap(tmp, $element, attrs);
});
}
};
});