[CCSDK-28] populated the seed code for dgbuilder
[ccsdk/distribution.git] / dgbuilder / public / red / ui / keyboard.js
1 /**
2  * Copyright 2013 IBM Corp.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  **/
16 RED.keyboard = (function() {
17
18     var active = true;
19     var handlers = {};
20
21     d3.select(window).on("keydown",function() {
22         if (!active) { return; }
23         var handler = handlers[d3.event.keyCode];
24         if (handler && handler.ondown) {
25             if (!handler.modifiers ||
26                 ((!handler.modifiers.shift || d3.event.shiftKey) &&
27                  (!handler.modifiers.ctrl  || d3.event.ctrlKey ) &&
28                  (!handler.modifiers.alt   || d3.event.altKey  ) )) {
29                 handler.ondown();
30             }
31         }
32     });
33     d3.select(window).on("keyup",function() {
34         if (!active) { return; }
35         var handler = handlers[d3.event.keyCode];
36         if (handler && handler.onup) {
37             if (!handler.modifiers ||
38                 ((!handler.modifiers.shift || d3.event.shiftKey) &&
39                  (!handler.modifiers.ctrl  || d3.event.ctrlKey ) &&
40                  (!handler.modifiers.alt   || d3.event.altKey  ) )) {
41                 handler.onup();
42             }
43         }
44     });
45     function addHandler(key,modifiers,ondown,onup) {
46         var mod = modifiers;
47         var cbdown = ondown;
48         var cbup = onup;
49
50         if (typeof modifiers == "function") {
51             mod = {};
52             cbdown = modifiers;
53             cbup = ondown;
54         }
55         handlers[key] = {modifiers:mod, ondown:cbdown, onup:cbup};
56     }
57     function removeHandler(key) {
58         delete handlers[key];
59     }
60
61     return {
62         add: addHandler,
63         remove: removeHandler,
64         disable: function(){ active = false;},
65         enable: function(){ active = true; }
66     }
67
68 })();