e2756a2151a34acc804e5df815b9bd91399ede6bf906af284810a39688c1760eb3199ff164597c59a220675f24b38a17243c03702c5ec03d48c03f21256966 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. /**
  2. * Utilities for mouse or touch events.
  3. */
  4. import Eventful from './Eventful';
  5. import env from './env';
  6. import { ZRRawEvent } from './types';
  7. import {isCanvasEl, transformCoordWithViewport} from './dom';
  8. const MOUSE_EVENT_REG = /^(?:mouse|pointer|contextmenu|drag|drop)|click/;
  9. const _calcOut: number[] = [];
  10. const firefoxNotSupportOffsetXY = env.browser.firefox
  11. // use offsetX/offsetY for Firefox >= 39
  12. // PENDING: consider Firefox for Android and Firefox OS? >= 43
  13. && +(env.browser.version as string).split('.')[0] < 39;
  14. type FirefoxMouseEvent = {
  15. layerX: number
  16. layerY: number
  17. }
  18. /**
  19. * Get the `zrX` and `zrY`, which are relative to the top-left of
  20. * the input `el`.
  21. * CSS transform (2D & 3D) is supported.
  22. *
  23. * The strategy to fetch the coords:
  24. * + If `calculate` is not set as `true`, users of this method should
  25. * ensure that `el` is the same or the same size & location as `e.target`.
  26. * Otherwise the result coords are probably not expected. Because we
  27. * firstly try to get coords from e.offsetX/e.offsetY.
  28. * + If `calculate` is set as `true`, the input `el` can be any element
  29. * and we force to calculate the coords based on `el`.
  30. * + The input `el` should be positionable (not position:static).
  31. *
  32. * The force `calculate` can be used in case like:
  33. * When mousemove event triggered on ec tooltip, `e.target` is not `el`(zr painter.dom).
  34. *
  35. * @param el DOM element.
  36. * @param e Mouse event or touch event.
  37. * @param out Get `out.zrX` and `out.zrY` as the result.
  38. * @param calculate Whether to force calculate
  39. * the coordinates but not use ones provided by browser.
  40. */
  41. export function clientToLocal(
  42. el: HTMLElement,
  43. e: ZRRawEvent | FirefoxMouseEvent | Touch,
  44. out: {zrX?: number, zrY?: number},
  45. calculate?: boolean
  46. ) {
  47. out = out || {};
  48. // According to the W3C Working Draft, offsetX and offsetY should be relative
  49. // to the padding edge of the target element. The only browser using this convention
  50. // is IE. Webkit uses the border edge, Opera uses the content edge, and FireFox does
  51. // not support the properties.
  52. // (see http://www.jacklmoore.com/notes/mouse-position/)
  53. // In zr painter.dom, padding edge equals to border edge.
  54. if (calculate) {
  55. calculateZrXY(el, e as ZRRawEvent, out);
  56. }
  57. // Caution: In FireFox, layerX/layerY Mouse position relative to the closest positioned
  58. // ancestor element, so we should make sure el is positioned (e.g., not position:static).
  59. // BTW1, Webkit don't return the same results as FF in non-simple cases (like add
  60. // zoom-factor, overflow / opacity layers, transforms ...)
  61. // BTW2, (ev.offsetY || ev.pageY - $(ev.target).offset().top) is not correct in preserve-3d.
  62. // <https://bugs.jquery.com/ticket/8523#comment:14>
  63. // BTW3, In ff, offsetX/offsetY is always 0.
  64. else if (firefoxNotSupportOffsetXY
  65. && (e as FirefoxMouseEvent).layerX != null
  66. && (e as FirefoxMouseEvent).layerX !== (e as MouseEvent).offsetX
  67. ) {
  68. out.zrX = (e as FirefoxMouseEvent).layerX;
  69. out.zrY = (e as FirefoxMouseEvent).layerY;
  70. }
  71. // For IE6+, chrome, safari, opera, firefox >= 39
  72. else if ((e as MouseEvent).offsetX != null) {
  73. out.zrX = (e as MouseEvent).offsetX;
  74. out.zrY = (e as MouseEvent).offsetY;
  75. }
  76. // For some other device, e.g., IOS safari.
  77. else {
  78. calculateZrXY(el, e as ZRRawEvent, out);
  79. }
  80. return out;
  81. }
  82. function calculateZrXY(
  83. el: HTMLElement,
  84. e: ZRRawEvent,
  85. out: {zrX?: number, zrY?: number}
  86. ) {
  87. // BlackBerry 5, iOS 3 (original iPhone) don't have getBoundingRect.
  88. if (env.domSupported && el.getBoundingClientRect) {
  89. const ex = (e as MouseEvent).clientX;
  90. const ey = (e as MouseEvent).clientY;
  91. if (isCanvasEl(el)) {
  92. // Original approach, which do not support CSS transform.
  93. // marker can not be locationed in a canvas container
  94. // (getBoundingClientRect is always 0). We do not support
  95. // that input a pre-created canvas to zr while using css
  96. // transform in iOS.
  97. const box = el.getBoundingClientRect();
  98. out.zrX = ex - box.left;
  99. out.zrY = ey - box.top;
  100. return;
  101. }
  102. else {
  103. if (transformCoordWithViewport(_calcOut, el, ex, ey)) {
  104. out.zrX = _calcOut[0];
  105. out.zrY = _calcOut[1];
  106. return;
  107. }
  108. }
  109. }
  110. out.zrX = out.zrY = 0;
  111. }
  112. /**
  113. * Find native event compat for legency IE.
  114. * Should be called at the begining of a native event listener.
  115. *
  116. * @param e Mouse event or touch event or pointer event.
  117. * For lagency IE, we use `window.event` is used.
  118. * @return The native event.
  119. */
  120. export function getNativeEvent(e: ZRRawEvent): ZRRawEvent {
  121. return e
  122. || (window.event as any); // For IE
  123. }
  124. /**
  125. * Normalize the coordinates of the input event.
  126. *
  127. * Get the `e.zrX` and `e.zrY`, which are relative to the top-left of
  128. * the input `el`.
  129. * Get `e.zrDelta` if using mouse wheel.
  130. * Get `e.which`, see the comment inside this function.
  131. *
  132. * Do not calculate repeatly if `zrX` and `zrY` already exist.
  133. *
  134. * Notice: see comments in `clientToLocal`. check the relationship
  135. * between the result coords and the parameters `el` and `calculate`.
  136. *
  137. * @param el DOM element.
  138. * @param e See `getNativeEvent`.
  139. * @param calculate Whether to force calculate
  140. * the coordinates but not use ones provided by browser.
  141. * @return The normalized native UIEvent.
  142. */
  143. export function normalizeEvent(
  144. el: HTMLElement,
  145. e: ZRRawEvent,
  146. calculate?: boolean
  147. ) {
  148. e = getNativeEvent(e);
  149. if (e.zrX != null) {
  150. return e;
  151. }
  152. const eventType = e.type;
  153. const isTouch = eventType && eventType.indexOf('touch') >= 0;
  154. if (!isTouch) {
  155. clientToLocal(el, e, e, calculate);
  156. const wheelDelta = getWheelDeltaMayPolyfill(e);
  157. // FIXME: IE8- has "wheelDeta" in event "mousewheel" but hat different value (120 times)
  158. // with Chrome and Safari. It's not correct for zrender event but we left it as it was.
  159. e.zrDelta = wheelDelta ? wheelDelta / 120 : -(e.detail || 0) / 3;
  160. }
  161. else {
  162. const touch = eventType !== 'touchend'
  163. ? (<TouchEvent>e).targetTouches[0]
  164. : (<TouchEvent>e).changedTouches[0];
  165. touch && clientToLocal(el, touch, e, calculate);
  166. }
  167. // Add which for click: 1 === left; 2 === middle; 3 === right; otherwise: 0;
  168. // See jQuery: https://github.com/jquery/jquery/blob/master/src/event.js
  169. // If e.which has been defined, it may be readonly,
  170. // see: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/which
  171. const button = (<MouseEvent>e).button;
  172. if (e.which == null && button !== undefined && MOUSE_EVENT_REG.test(e.type)) {
  173. (e as any).which = (button & 1 ? 1 : (button & 2 ? 3 : (button & 4 ? 2 : 0)));
  174. }
  175. // [Caution]: `e.which` from browser is not always reliable. For example,
  176. // when press left button and `mousemove (pointermove)` in Edge, the `e.which`
  177. // is 65536 and the `e.button` is -1. But the `mouseup (pointerup)` and
  178. // `mousedown (pointerdown)` is the same as Chrome does.
  179. return e;
  180. }
  181. // TODO: also provide prop "deltaX" "deltaY" in zrender "mousewheel" event.
  182. function getWheelDeltaMayPolyfill(e: ZRRawEvent): number {
  183. // Although event "wheel" do not has the prop "wheelDelta" in spec,
  184. // agent like Chrome and Safari still provide "wheelDelta" like
  185. // event "mousewheel" did (perhaps for backward compat).
  186. // Since zrender has been using "wheelDeta" in zrender event "mousewheel".
  187. // we currently do not break it.
  188. // But event "wheel" in firefox do not has "wheelDelta", so we calculate
  189. // "wheelDeta" from "deltaX", "deltaY" (which is the props in spec).
  190. const rawWheelDelta = (e as any).wheelDelta;
  191. // Theroetically `e.wheelDelta` won't be 0 unless some day it has been deprecated
  192. // by agent like Chrome or Safari. So we also calculate it if rawWheelDelta is 0.
  193. if (rawWheelDelta) {
  194. return rawWheelDelta;
  195. }
  196. const deltaX = (e as any).deltaX;
  197. const deltaY = (e as any).deltaY;
  198. if (deltaX == null || deltaY == null) {
  199. return rawWheelDelta;
  200. }
  201. // Test in Chrome and Safari (MacOS):
  202. // The sign is corrent.
  203. // The abs value is 99% corrent (inconsist case only like 62~63, 125~126 ...)
  204. const delta = deltaY !== 0 ? Math.abs(deltaY) : Math.abs(deltaX);
  205. const sign = deltaY > 0 ? -1
  206. : deltaY < 0 ? 1
  207. : deltaX > 0 ? -1
  208. : 1;
  209. return 3 * delta * sign;
  210. }
  211. type AddEventListenerParams = Parameters<typeof HTMLElement.prototype.addEventListener>
  212. type RemoveEventListenerParams = Parameters<typeof HTMLElement.prototype.removeEventListener>
  213. /**
  214. * @param el
  215. * @param name
  216. * @param handler
  217. * @param opt If boolean, means `opt.capture`
  218. * @param opt.capture
  219. * @param opt.passive
  220. */
  221. export function addEventListener(
  222. el: HTMLElement | HTMLDocument,
  223. name: AddEventListenerParams[0],
  224. handler: AddEventListenerParams[1],
  225. opt?: AddEventListenerParams[2]
  226. ) {
  227. // Reproduct the console warning:
  228. // [Violation] Added non-passive event listener to a scroll-blocking <some> event.
  229. // Consider marking event handler as 'passive' to make the page more responsive.
  230. // Just set console log level: verbose in chrome dev tool.
  231. // then the warning log will be printed when addEventListener called.
  232. // See https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md
  233. // We have not yet found a neat way to using passive. Because in zrender the dom event
  234. // listener delegate all of the upper events of element. Some of those events need
  235. // to prevent default. For example, the feature `preventDefaultMouseMove` of echarts.
  236. // Before passive can be adopted, these issues should be considered:
  237. // (1) Whether and how a zrender user specifies an event listener passive. And by default,
  238. // passive or not.
  239. // (2) How to tread that some zrender event listener is passive, and some is not. If
  240. // we use other way but not preventDefault of mousewheel and touchmove, browser
  241. // compatibility should be handled.
  242. // const opts = (env.passiveSupported && name === 'mousewheel')
  243. // ? {passive: true}
  244. // // By default, the third param of el.addEventListener is `capture: false`.
  245. // : void 0;
  246. // el.addEventListener(name, handler /* , opts */);
  247. el.addEventListener(name, handler, opt);
  248. }
  249. /**
  250. * Parameter are the same as `addEventListener`.
  251. *
  252. * Notice that if a listener is registered twice, one with capture and one without,
  253. * remove each one separately. Removal of a capturing listener does not affect a
  254. * non-capturing version of the same listener, and vice versa.
  255. */
  256. export function removeEventListener(
  257. el: HTMLElement | HTMLDocument,
  258. name: RemoveEventListenerParams[0],
  259. handler: RemoveEventListenerParams[1],
  260. opt: RemoveEventListenerParams[2]
  261. ) {
  262. el.removeEventListener(name, handler, opt);
  263. }
  264. /**
  265. * preventDefault and stopPropagation.
  266. * Notice: do not use this method in zrender. It can only be
  267. * used by upper applications if necessary.
  268. *
  269. * @param {Event} e A mouse or touch event.
  270. */
  271. export const stop = function (e: MouseEvent | TouchEvent | PointerEvent) {
  272. e.preventDefault();
  273. e.stopPropagation();
  274. e.cancelBubble = true;
  275. };
  276. /**
  277. * This method only works for mouseup and mousedown. The functionality is restricted
  278. * for fault tolerance, See the `e.which` compatibility above.
  279. *
  280. * params can be MouseEvent or ElementEvent
  281. */
  282. export function isMiddleOrRightButtonOnMouseUpDown(e: { which: number }) {
  283. return e.which === 2 || e.which === 3;
  284. }
  285. // For backward compatibility
  286. export {Eventful as Dispatcher};