Keys.hx 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package hide.ui;
  2. class Keys {
  3. var keys = new Map<String,Void->Void>();
  4. var parent : js.html.Element;
  5. var listeners = new Array<js.jquery.Event -> Bool>();
  6. public function new( parent : Element ) {
  7. if( parent != null ) {
  8. this.parent = parent[0];
  9. parent.attr("haskeys","true");
  10. if( this.parent != null ) Reflect.setField(this.parent,"__keys",this);
  11. }
  12. }
  13. public function remove() {
  14. if( parent != null ) {
  15. Reflect.deleteField(parent,"__keys");
  16. parent.removeAttribute("haskeys");
  17. }
  18. }
  19. public function addListener( l ) {
  20. listeners.push(l);
  21. }
  22. public function processEvent( e : js.jquery.Event, config : Config ) {
  23. var parts = [];
  24. if( e.altKey )
  25. parts.push("Alt");
  26. if( e.ctrlKey )
  27. parts.push("Ctrl");
  28. if( e.shiftKey )
  29. parts.push("Shift");
  30. if( e.keyCode == hxd.Key.ALT || e.keyCode == hxd.Key.SHIFT || e.keyCode == hxd.Key.CTRL ) {
  31. //
  32. } else {
  33. var name = hxd.Key.getKeyName(e.keyCode);
  34. if( name != null )
  35. parts.push(name);
  36. else if( e.key != "" )
  37. parts.push(e.key);
  38. else
  39. parts.push(""+e.keyCode);
  40. }
  41. var key = parts.join("-");
  42. if( triggerKey(e, key, config) ) {
  43. e.stopPropagation();
  44. e.preventDefault();
  45. return true;
  46. }
  47. return false;
  48. }
  49. public function triggerKey( e : js.jquery.Event, key : String, config : Config ) {
  50. for( l in listeners )
  51. if( l(e) )
  52. return true;
  53. for( k in keys.keys() ) {
  54. var keyCode = config.get("key."+k);
  55. if( keyCode == null ) {
  56. trace("Key not defined " + k);
  57. continue;
  58. }
  59. if( keyCode == key ) {
  60. keys.get(k)();
  61. return true;
  62. }
  63. }
  64. return false;
  65. }
  66. public function register( name : String, callb : Void -> Void ) {
  67. keys.set(name, callb);
  68. }
  69. public static function get( e : Element ) : Keys {
  70. return Reflect.field(e[0], "__keys");
  71. }
  72. }