touch.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. // Copyright 2013 The Closure Library Authors. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS-IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. /**
  15. * @fileoverview Utilities to abstract mouse and touch events.
  16. */
  17. goog.provide('goog.labs.events.touch');
  18. goog.provide('goog.labs.events.touch.TouchData');
  19. goog.require('goog.array');
  20. goog.require('goog.asserts');
  21. goog.require('goog.events.EventType');
  22. goog.require('goog.string');
  23. /**
  24. * Description the geometry and target of an event.
  25. *
  26. * @typedef {{
  27. * clientX: number,
  28. * clientY: number,
  29. * screenX: number,
  30. * screenY: number,
  31. * target: EventTarget
  32. * }}
  33. */
  34. goog.labs.events.touch.TouchData;
  35. /**
  36. * Takes a mouse or touch event and returns the relevant geometry and target
  37. * data.
  38. * @param {!Event} e A mouse or touch event.
  39. * @return {!goog.labs.events.touch.TouchData}
  40. */
  41. goog.labs.events.touch.getTouchData = function(e) {
  42. var source = e;
  43. goog.asserts.assert(
  44. goog.string.startsWith(e.type, 'touch') ||
  45. goog.string.startsWith(e.type, 'mouse'),
  46. 'Event must be mouse or touch event.');
  47. if (goog.string.startsWith(e.type, 'touch')) {
  48. goog.asserts.assert(
  49. goog.array.contains(
  50. [
  51. goog.events.EventType.TOUCHCANCEL, goog.events.EventType.TOUCHEND,
  52. goog.events.EventType.TOUCHMOVE, goog.events.EventType.TOUCHSTART
  53. ],
  54. e.type),
  55. 'Touch event not of valid type.');
  56. // If the event is end or cancel, take the first changed touch,
  57. // otherwise the first target touch.
  58. source = (e.type == goog.events.EventType.TOUCHEND ||
  59. e.type == goog.events.EventType.TOUCHCANCEL) ?
  60. e.changedTouches[0] :
  61. e.targetTouches[0];
  62. }
  63. return {
  64. clientX: source['clientX'],
  65. clientY: source['clientY'],
  66. screenX: source['screenX'],
  67. screenY: source['screenY'],
  68. target: source['target']
  69. };
  70. };