HandlerProxy.js 17 KB

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