You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

69 lines
2.2KB

  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. var active = true;
  18. var handlers = {};
  19. d3.select(window).on("keydown",function() {
  20. if (!active) { return; }
  21. var handler = handlers[d3.event.keyCode];
  22. if (handler && handler.ondown) {
  23. if (!handler.modifiers ||
  24. ((!handler.modifiers.shift || d3.event.shiftKey) &&
  25. (!handler.modifiers.ctrl || d3.event.ctrlKey ) &&
  26. (!handler.modifiers.alt || d3.event.altKey ) )) {
  27. handler.ondown();
  28. }
  29. }
  30. });
  31. d3.select(window).on("keyup",function() {
  32. if (!active) { return; }
  33. var handler = handlers[d3.event.keyCode];
  34. if (handler && handler.onup) {
  35. if (!handler.modifiers ||
  36. ((!handler.modifiers.shift || d3.event.shiftKey) &&
  37. (!handler.modifiers.ctrl || d3.event.ctrlKey ) &&
  38. (!handler.modifiers.alt || d3.event.altKey ) )) {
  39. handler.onup();
  40. }
  41. }
  42. });
  43. function addHandler(key,modifiers,ondown,onup) {
  44. var mod = modifiers;
  45. var cbdown = ondown;
  46. var cbup = onup;
  47. if (typeof modifiers == "function") {
  48. mod = {};
  49. cbdown = modifiers;
  50. cbup = ondown;
  51. }
  52. handlers[key] = {modifiers:mod, ondown:cbdown, onup:cbup};
  53. }
  54. function removeHandler(key) {
  55. delete handlers[key];
  56. }
  57. return {
  58. add: addHandler,
  59. remove: removeHandler,
  60. disable: function(){ active = false;},
  61. enable: function(){ active = true; }
  62. }
  63. })();