HandlerProxy.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. var _event = require("../core/event");
  2. var addEventListener = _event.addEventListener;
  3. var removeEventListener = _event.removeEventListener;
  4. var normalizeEvent = _event.normalizeEvent;
  5. var getNativeEvent = _event.getNativeEvent;
  6. var zrUtil = require("../core/util");
  7. var Eventful = require("../mixin/Eventful");
  8. var env = require("../core/env");
  9. /* global document */
  10. var TOUCH_CLICK_DELAY = 300;
  11. var globalEventSupported = env.domSupported;
  12. var localNativeListenerNames = function () {
  13. var mouseHandlerNames = ['click', 'dblclick', 'mousewheel', 'mouseout', 'mouseup', 'mousedown', 'mousemove', 'contextmenu'];
  14. var touchHandlerNames = ['touchstart', 'touchend', 'touchmove'];
  15. var pointerEventNameMap = {
  16. pointerdown: 1,
  17. pointerup: 1,
  18. pointermove: 1,
  19. pointerout: 1
  20. };
  21. var pointerHandlerNames = zrUtil.map(mouseHandlerNames, function (name) {
  22. var nm = name.replace('mouse', 'pointer');
  23. return pointerEventNameMap.hasOwnProperty(nm) ? nm : name;
  24. });
  25. return {
  26. mouse: mouseHandlerNames,
  27. touch: touchHandlerNames,
  28. pointer: pointerHandlerNames
  29. };
  30. }();
  31. var globalNativeListenerNames = {
  32. mouse: ['mousemove', 'mouseup'],
  33. pointer: ['pointermove', 'pointerup']
  34. };
  35. function eventNameFix(name) {
  36. return name === 'mousewheel' && env.browser.firefox ? 'DOMMouseScroll' : name;
  37. }
  38. function isPointerFromTouch(event) {
  39. var pointerType = event.pointerType;
  40. return pointerType === 'pen' || pointerType === 'touch';
  41. } // function useMSGuesture(handlerProxy, event) {
  42. // return isPointerFromTouch(event) && !!handlerProxy._msGesture;
  43. // }
  44. // function onMSGestureChange(proxy, event) {
  45. // if (event.translationX || event.translationY) {
  46. // // mousemove is carried by MSGesture to reduce the sensitivity.
  47. // proxy.handler.dispatchToElement(event.target, 'mousemove', event);
  48. // }
  49. // if (event.scale !== 1) {
  50. // event.pinchX = event.offsetX;
  51. // event.pinchY = event.offsetY;
  52. // event.pinchScale = event.scale;
  53. // proxy.handler.dispatchToElement(event.target, 'pinch', event);
  54. // }
  55. // }
  56. /**
  57. * Prevent mouse event from being dispatched after Touch Events action
  58. * @see <https://github.com/deltakosh/handjs/blob/master/src/hand.base.js>
  59. * 1. Mobile browsers dispatch mouse events 300ms after touchend.
  60. * 2. Chrome for Android dispatch mousedown for long-touch about 650ms
  61. * Result: Blocking Mouse Events for 700ms.
  62. *
  63. * @param {DOMHandlerScope} scope
  64. */
  65. function setTouchTimer(scope) {
  66. scope.touching = true;
  67. if (scope.touchTimer != null) {
  68. clearTimeout(scope.touchTimer);
  69. scope.touchTimer = null;
  70. }
  71. scope.touchTimer = setTimeout(function () {
  72. scope.touching = false;
  73. scope.touchTimer = null;
  74. }, 700);
  75. } // Mark touch, which is useful in distinguish touch and
  76. // mouse event in upper applicatoin.
  77. function markTouch(event) {
  78. event && (event.zrByTouch = true);
  79. } // function markTriggeredFromLocal(event) {
  80. // event && (event.__zrIsFromLocal = true);
  81. // }
  82. // function isTriggeredFromLocal(instance, event) {
  83. // return !!(event && event.__zrIsFromLocal);
  84. // }
  85. function normalizeGlobalEvent(instance, event) {
  86. // offsetX, offsetY still need to be calculated. They are necessary in the event
  87. // handlers of the upper applications. Set `true` to force calculate them.
  88. return normalizeEvent(instance.dom, new FakeGlobalEvent(instance, event), true);
  89. }
  90. /**
  91. * Detect whether the given el is in `painterRoot`.
  92. */
  93. function isLocalEl(instance, el) {
  94. var elTmp = el;
  95. var isLocal = false;
  96. while (elTmp && elTmp.nodeType !== 9 && !(isLocal = elTmp.domBelongToZr || elTmp !== el && elTmp === instance.painterRoot)) {
  97. elTmp = elTmp.parentNode;
  98. }
  99. return isLocal;
  100. }
  101. /**
  102. * Make a fake event but not change the original event,
  103. * becuase the global event probably be used by other
  104. * listeners not belonging to zrender.
  105. * @class
  106. */
  107. function FakeGlobalEvent(instance, event) {
  108. this.type = event.type;
  109. this.target = this.currentTarget = instance.dom;
  110. this.pointerType = event.pointerType; // Necessray for the force calculation of zrX, zrY
  111. this.clientX = event.clientX;
  112. this.clientY = event.clientY; // Because we do not mount global listeners to touch events,
  113. // we do not copy `targetTouches` and `changedTouches` here.
  114. }
  115. var fakeGlobalEventProto = FakeGlobalEvent.prototype; // we make the default methods on the event do nothing,
  116. // otherwise it is dangerous. See more details in
  117. // [Drag outside] in `Handler.js`.
  118. fakeGlobalEventProto.stopPropagation = fakeGlobalEventProto.stopImmediatePropagation = fakeGlobalEventProto.preventDefault = zrUtil.noop;
  119. /**
  120. * Local DOM Handlers
  121. * @this {HandlerProxy}
  122. */
  123. var localDOMHandlers = {
  124. mousedown: function (event) {
  125. event = normalizeEvent(this.dom, event);
  126. this._mayPointerCapture = [event.zrX, event.zrY];
  127. this.trigger('mousedown', event);
  128. },
  129. mousemove: function (event) {
  130. event = normalizeEvent(this.dom, event);
  131. var downPoint = this._mayPointerCapture;
  132. if (downPoint && (event.zrX !== downPoint[0] || event.zrY !== downPoint[1])) {
  133. togglePointerCapture(this, true);
  134. }
  135. this.trigger('mousemove', event);
  136. },
  137. mouseup: function (event) {
  138. event = normalizeEvent(this.dom, event);
  139. togglePointerCapture(this, false);
  140. this.trigger('mouseup', event);
  141. },
  142. mouseout: function (event) {
  143. event = normalizeEvent(this.dom, event); // Similarly to the browser did on `document` and touch event,
  144. // `globalout` will be delayed to final pointer cature release.
  145. if (this._pointerCapturing) {
  146. event.zrEventControl = 'no_globalout';
  147. } // There might be some doms created by upper layer application
  148. // at the same level of painter.getViewportRoot() (e.g., tooltip
  149. // dom created by echarts), where 'globalout' event should not
  150. // be triggered when mouse enters these doms. (But 'mouseout'
  151. // should be triggered at the original hovered element as usual).
  152. var element = event.toElement || event.relatedTarget;
  153. event.zrIsToLocalDOM = isLocalEl(this, element);
  154. this.trigger('mouseout', event);
  155. },
  156. touchstart: function (event) {
  157. // Default mouse behaviour should not be disabled here.
  158. // For example, page may needs to be slided.
  159. event = normalizeEvent(this.dom, event);
  160. markTouch(event);
  161. this._lastTouchMoment = new Date();
  162. this.handler.processGesture(event, 'start'); // For consistent event listener for both touch device and mouse device,
  163. // we simulate "mouseover-->mousedown" in touch device. So we trigger
  164. // `mousemove` here (to trigger `mouseover` inside), and then trigger
  165. // `mousedown`.
  166. localDOMHandlers.mousemove.call(this, event);
  167. localDOMHandlers.mousedown.call(this, event);
  168. },
  169. touchmove: function (event) {
  170. event = normalizeEvent(this.dom, event);
  171. markTouch(event);
  172. this.handler.processGesture(event, 'change'); // Mouse move should always be triggered no matter whether
  173. // there is gestrue event, because mouse move and pinch may
  174. // be used at the same time.
  175. localDOMHandlers.mousemove.call(this, event);
  176. },
  177. touchend: function (event) {
  178. event = normalizeEvent(this.dom, event);
  179. markTouch(event);
  180. this.handler.processGesture(event, 'end');
  181. localDOMHandlers.mouseup.call(this, event); // Do not trigger `mouseout` here, in spite of `mousemove`(`mouseover`) is
  182. // triggered in `touchstart`. This seems to be illogical, but by this mechanism,
  183. // we can conveniently implement "hover style" in both PC and touch device just
  184. // by listening to `mouseover` to add "hover style" and listening to `mouseout`
  185. // to remove "hover style" on an element, without any additional code for
  186. // compatibility. (`mouseout` will not be triggered in `touchend`, so "hover
  187. // style" will remain for user view)
  188. // click event should always be triggered no matter whether
  189. // there is gestrue event. System click can not be prevented.
  190. if (+new Date() - this._lastTouchMoment < TOUCH_CLICK_DELAY) {
  191. localDOMHandlers.click.call(this, event);
  192. }
  193. },
  194. pointerdown: function (event) {
  195. localDOMHandlers.mousedown.call(this, event); // if (useMSGuesture(this, event)) {
  196. // this._msGesture.addPointer(event.pointerId);
  197. // }
  198. },
  199. pointermove: function (event) {
  200. // FIXME
  201. // pointermove is so sensitive that it always triggered when
  202. // tap(click) on touch screen, which affect some judgement in
  203. // upper application. So, we dont support mousemove on MS touch
  204. // device yet.
  205. if (!isPointerFromTouch(event)) {
  206. localDOMHandlers.mousemove.call(this, event);
  207. }
  208. },
  209. pointerup: function (event) {
  210. localDOMHandlers.mouseup.call(this, event);
  211. },
  212. pointerout: function (event) {
  213. // pointerout will be triggered when tap on touch screen
  214. // (IE11+/Edge on MS Surface) after click event triggered,
  215. // which is inconsistent with the mousout behavior we defined
  216. // in touchend. So we unify them.
  217. // (check localDOMHandlers.touchend for detailed explanation)
  218. if (!isPointerFromTouch(event)) {
  219. localDOMHandlers.mouseout.call(this, event);
  220. }
  221. }
  222. };
  223. /**
  224. * Othere DOM UI Event handlers for zr dom.
  225. * @this {HandlerProxy}
  226. */
  227. zrUtil.each(['click', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  228. localDOMHandlers[name] = function (event) {
  229. event = normalizeEvent(this.dom, event);
  230. this.trigger(name, event);
  231. };
  232. });
  233. /**
  234. * DOM UI Event handlers for global page.
  235. *
  236. * [Caution]:
  237. * those handlers should both support in capture phase and bubble phase!
  238. *
  239. * @this {HandlerProxy}
  240. */
  241. var globalDOMHandlers = {
  242. pointermove: function (event) {
  243. // FIXME
  244. // pointermove is so sensitive that it always triggered when
  245. // tap(click) on touch screen, which affect some judgement in
  246. // upper application. So, we dont support mousemove on MS touch
  247. // device yet.
  248. if (!isPointerFromTouch(event)) {
  249. globalDOMHandlers.mousemove.call(this, event);
  250. }
  251. },
  252. pointerup: function (event) {
  253. globalDOMHandlers.mouseup.call(this, event);
  254. },
  255. mousemove: function (event) {
  256. this.trigger('mousemove', event);
  257. },
  258. mouseup: function (event) {
  259. var pointerCaptureReleasing = this._pointerCapturing;
  260. togglePointerCapture(this, false);
  261. this.trigger('mouseup', event);
  262. if (pointerCaptureReleasing) {
  263. event.zrEventControl = 'only_globalout';
  264. this.trigger('mouseout', event);
  265. }
  266. }
  267. };
  268. /**
  269. * @param {HandlerProxy} instance
  270. * @param {DOMHandlerScope} scope
  271. */
  272. function mountLocalDOMEventListeners(instance, scope) {
  273. var domHandlers = scope.domHandlers;
  274. if (env.pointerEventsSupported) {
  275. // Only IE11+/Edge
  276. // 1. On devices that both enable touch and mouse (e.g., MS Surface and lenovo X240),
  277. // IE11+/Edge do not trigger touch event, but trigger pointer event and mouse event
  278. // at the same time.
  279. // 2. On MS Surface, it probablely only trigger mousedown but no mouseup when tap on
  280. // screen, which do not occurs in pointer event.
  281. // So we use pointer event to both detect touch gesture and mouse behavior.
  282. zrUtil.each(localNativeListenerNames.pointer, function (nativeEventName) {
  283. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  284. // markTriggeredFromLocal(event);
  285. domHandlers[nativeEventName].call(instance, event);
  286. });
  287. }); // FIXME
  288. // Note: MS Gesture require CSS touch-action set. But touch-action is not reliable,
  289. // which does not prevent defuault behavior occasionally (which may cause view port
  290. // zoomed in but use can not zoom it back). And event.preventDefault() does not work.
  291. // So we have to not to use MSGesture and not to support touchmove and pinch on MS
  292. // touch screen. And we only support click behavior on MS touch screen now.
  293. // MS Gesture Event is only supported on IE11+/Edge and on Windows 8+.
  294. // We dont support touch on IE on win7.
  295. // See <https://msdn.microsoft.com/en-us/library/dn433243(v=vs.85).aspx>
  296. // if (typeof MSGesture === 'function') {
  297. // (this._msGesture = new MSGesture()).target = dom; // jshint ignore:line
  298. // dom.addEventListener('MSGestureChange', onMSGestureChange);
  299. // }
  300. } else {
  301. if (env.touchEventsSupported) {
  302. zrUtil.each(localNativeListenerNames.touch, function (nativeEventName) {
  303. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  304. // markTriggeredFromLocal(event);
  305. domHandlers[nativeEventName].call(instance, event);
  306. setTouchTimer(scope);
  307. });
  308. }); // Handler of 'mouseout' event is needed in touch mode, which will be mounted below.
  309. // addEventListener(root, 'mouseout', this._mouseoutHandler);
  310. } // 1. Considering some devices that both enable touch and mouse event (like on MS Surface
  311. // and lenovo X240, @see #2350), we make mouse event be always listened, otherwise
  312. // mouse event can not be handle in those devices.
  313. // 2. On MS Surface, Chrome will trigger both touch event and mouse event. How to prevent
  314. // mouseevent after touch event triggered, see `setTouchTimer`.
  315. zrUtil.each(localNativeListenerNames.mouse, function (nativeEventName) {
  316. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  317. event = getNativeEvent(event);
  318. if (!scope.touching) {
  319. // markTriggeredFromLocal(event);
  320. domHandlers[nativeEventName].call(instance, event);
  321. }
  322. });
  323. });
  324. }
  325. }
  326. /**
  327. * @param {HandlerProxy} instance
  328. * @param {DOMHandlerScope} scope
  329. */
  330. function mountGlobalDOMEventListeners(instance, scope) {
  331. // Only IE11+/Edge. See the comment in `mountLocalDOMEventListeners`.
  332. if (env.pointerEventsSupported) {
  333. zrUtil.each(globalNativeListenerNames.pointer, mount);
  334. } // Touch event has implemented "drag outside" so we do not mount global listener for touch event.
  335. // (see https://www.w3.org/TR/touch-events/#the-touchmove-event)
  336. // We do not consider "both-support-touch-and-mouse device" for this feature (see the comment of
  337. // `mountLocalDOMEventListeners`) to avoid bugs util some requirements come.
  338. else if (!env.touchEventsSupported) {
  339. zrUtil.each(globalNativeListenerNames.mouse, mount);
  340. }
  341. function mount(nativeEventName) {
  342. function nativeEventListener(event) {
  343. event = getNativeEvent(event); // See the reason in [Drag outside] in `Handler.js`
  344. // This checking supports both `useCapture` or not.
  345. // PENDING: if there is performance issue in some devices,
  346. // we probably can not use `useCapture` and change a easier
  347. // to judes whether local (mark).
  348. if (!isLocalEl(instance, event.target)) {
  349. event = normalizeGlobalEvent(instance, event);
  350. scope.domHandlers[nativeEventName].call(instance, event);
  351. }
  352. }
  353. mountSingleDOMEventListener(scope, nativeEventName, nativeEventListener, {
  354. capture: true
  355. } // See [Drag Outside] in `Handler.js`
  356. );
  357. }
  358. }
  359. function mountSingleDOMEventListener(scope, nativeEventName, listener, opt) {
  360. scope.mounted[nativeEventName] = listener;
  361. scope.listenerOpts[nativeEventName] = opt;
  362. addEventListener(scope.domTarget, eventNameFix(nativeEventName), listener, opt);
  363. }
  364. function unmountDOMEventListeners(scope) {
  365. var mounted = scope.mounted;
  366. for (var nativeEventName in mounted) {
  367. if (mounted.hasOwnProperty(nativeEventName)) {
  368. removeEventListener(scope.domTarget, eventNameFix(nativeEventName), mounted[nativeEventName], scope.listenerOpts[nativeEventName]);
  369. }
  370. }
  371. scope.mounted = {};
  372. }
  373. /**
  374. * See [Drag Outside] in `Handler.js`.
  375. * @implement
  376. * @param {boolean} isPointerCapturing Should never be `null`/`undefined`.
  377. * `true`: start to capture pointer if it is not capturing.
  378. * `false`: end the capture if it is capturing.
  379. */
  380. function togglePointerCapture(instance, isPointerCapturing) {
  381. instance._mayPointerCapture = null;
  382. if (globalEventSupported && instance._pointerCapturing ^ isPointerCapturing) {
  383. instance._pointerCapturing = isPointerCapturing;
  384. var globalHandlerScope = instance._globalHandlerScope;
  385. isPointerCapturing ? mountGlobalDOMEventListeners(instance, globalHandlerScope) : unmountDOMEventListeners(globalHandlerScope);
  386. }
  387. }
  388. /**
  389. * @inner
  390. * @class
  391. */
  392. function DOMHandlerScope(domTarget, domHandlers) {
  393. this.domTarget = domTarget;
  394. this.domHandlers = domHandlers; // Key: eventName, value: mounted handler funcitons.
  395. // Used for unmount.
  396. this.mounted = {};
  397. this.listenerOpts = {};
  398. this.touchTimer = null;
  399. this.touching = false;
  400. }
  401. /**
  402. * @public
  403. * @class
  404. */
  405. function HandlerDomProxy(dom, painterRoot) {
  406. Eventful.call(this);
  407. this.dom = dom;
  408. this.painterRoot = painterRoot;
  409. this._localHandlerScope = new DOMHandlerScope(dom, localDOMHandlers);
  410. if (globalEventSupported) {
  411. this._globalHandlerScope = new DOMHandlerScope(document, globalDOMHandlers);
  412. }
  413. /**
  414. * @type {boolean}
  415. */
  416. this._pointerCapturing = false;
  417. /**
  418. * @type {Array.<number>} [x, y] or null.
  419. */
  420. this._mayPointerCapture = null;
  421. mountLocalDOMEventListeners(this, this._localHandlerScope);
  422. }
  423. var handlerDomProxyProto = HandlerDomProxy.prototype;
  424. handlerDomProxyProto.dispose = function () {
  425. unmountDOMEventListeners(this._localHandlerScope);
  426. if (globalEventSupported) {
  427. unmountDOMEventListeners(this._globalHandlerScope);
  428. }
  429. };
  430. handlerDomProxyProto.setCursor = function (cursorStyle) {
  431. this.dom.style && (this.dom.style.cursor = cursorStyle || 'default');
  432. };
  433. zrUtil.mixin(HandlerDomProxy, Eventful);
  434. var _default = HandlerDomProxy;
  435. module.exports = _default;