Handler.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. var util = require("./core/util");
  2. var vec2 = require("./core/vector");
  3. var Draggable = require("./mixin/Draggable");
  4. var Eventful = require("./mixin/Eventful");
  5. var eventTool = require("./core/event");
  6. var GestureMgr = require("./core/GestureMgr");
  7. /**
  8. * [The interface between `Handler` and `HandlerProxy`]:
  9. *
  10. * The default `HandlerProxy` only support the common standard web environment
  11. * (e.g., standalone browser, headless browser, embed browser in mobild APP, ...).
  12. * But `HandlerProxy` can be replaced to support more non-standard environment
  13. * (e.g., mini app), or to support more feature that the default `HandlerProxy`
  14. * not provided (like echarts-gl did).
  15. * So the interface between `Handler` and `HandlerProxy` should be stable. Do not
  16. * make break changes util inevitable. The interface include the public methods
  17. * of `Handler` and the events listed in `handlerNames` below, by which `HandlerProxy`
  18. * drives `Handler`.
  19. */
  20. /**
  21. * [Drag outside]:
  22. *
  23. * That is, triggering `mousemove` and `mouseup` event when the pointer is out of the
  24. * zrender area when dragging. That is important for the improvement of the user experience
  25. * when dragging something near the boundary without being terminated unexpectedly.
  26. *
  27. * We originally consider to introduce new events like `pagemovemove` and `pagemouseup`
  28. * to resolve this issue. But some drawbacks of it is described in
  29. * https://github.com/ecomfe/zrender/pull/536#issuecomment-560286899
  30. *
  31. * Instead, we referenced the specifications:
  32. * https://www.w3.org/TR/touch-events/#the-touchmove-event
  33. * https://www.w3.org/TR/2014/WD-DOM-Level-3-Events-20140925/#event-type-mousemove
  34. * where the the mousemove/touchmove can be continue to fire if the user began a drag
  35. * operation and the pointer has left the boundary. (for the mouse event, browsers
  36. * only do it on `document` and when the pointer has left the boundary of the browser.)
  37. *
  38. * So the default `HandlerProxy` supports this feature similarly: if it is in the dragging
  39. * state (see `pointerCapture` in `HandlerProxy`), the `mousemove` and `mouseup` continue
  40. * to fire until release the pointer. That is implemented by listen to those event on
  41. * `document`.
  42. * If we implement some other `HandlerProxy` only for touch device, that would be easier.
  43. * The touch event support this feature by default.
  44. *
  45. * Note:
  46. * There might be some cases that the mouse event can not be
  47. * received on `document`. For example,
  48. * (A) `useCapture` is not supported and some user defined event listeners on the ancestor
  49. * of zr dom throw Error .
  50. * (B) `useCapture` is not supported Some user defined event listeners on the ancestor of
  51. * zr dom call `stopPropagation`.
  52. * In these cases, the `mousemove` event might be keep triggered event
  53. * if the mouse is released. We try to reduce the side-effect in those cases.
  54. * That is, do nothing (especially, `findHover`) in those cases. See `isOutsideBoundary`.
  55. *
  56. * Note:
  57. * If `HandlerProxy` listens to `document` with `useCapture`, `HandlerProxy` needs to
  58. * make sure `stopPropagation` and `preventDefault` doing nothing if and only if the event
  59. * target is not zrender dom. Becuase it is dangerous to enable users to call them in
  60. * `document` capture phase to prevent the propagation to any listener of the webpage.
  61. * But they are needed to work when the pointer inside the zrender dom.
  62. */
  63. var SILENT = 'silent';
  64. function makeEventPacket(eveType, targetInfo, event) {
  65. return {
  66. type: eveType,
  67. event: event,
  68. // target can only be an element that is not silent.
  69. target: targetInfo.target,
  70. // topTarget can be a silent element.
  71. topTarget: targetInfo.topTarget,
  72. cancelBubble: false,
  73. offsetX: event.zrX,
  74. offsetY: event.zrY,
  75. gestureEvent: event.gestureEvent,
  76. pinchX: event.pinchX,
  77. pinchY: event.pinchY,
  78. pinchScale: event.pinchScale,
  79. wheelDelta: event.zrDelta,
  80. zrByTouch: event.zrByTouch,
  81. which: event.which,
  82. stop: stopEvent
  83. };
  84. }
  85. function stopEvent() {
  86. eventTool.stop(this.event);
  87. }
  88. function EmptyProxy() {}
  89. EmptyProxy.prototype.dispose = function () {};
  90. var handlerNames = ['click', 'dblclick', 'mousewheel', 'mouseout', 'mouseup', 'mousedown', 'mousemove', 'contextmenu'];
  91. /**
  92. * @alias module:zrender/Handler
  93. * @constructor
  94. * @extends module:zrender/mixin/Eventful
  95. * @param {module:zrender/Storage} storage Storage instance.
  96. * @param {module:zrender/Painter} painter Painter instance.
  97. * @param {module:zrender/dom/HandlerProxy} proxy HandlerProxy instance.
  98. * @param {HTMLElement} painterRoot painter.root (not painter.getViewportRoot()).
  99. */
  100. var Handler = function (storage, painter, proxy, painterRoot) {
  101. Eventful.call(this);
  102. this.storage = storage;
  103. this.painter = painter;
  104. this.painterRoot = painterRoot;
  105. proxy = proxy || new EmptyProxy();
  106. /**
  107. * Proxy of event. can be Dom, WebGLSurface, etc.
  108. */
  109. this.proxy = null;
  110. /**
  111. * {target, topTarget, x, y}
  112. * @private
  113. * @type {Object}
  114. */
  115. this._hovered = {};
  116. /**
  117. * @private
  118. * @type {Date}
  119. */
  120. this._lastTouchMoment;
  121. /**
  122. * @private
  123. * @type {number}
  124. */
  125. this._lastX;
  126. /**
  127. * @private
  128. * @type {number}
  129. */
  130. this._lastY;
  131. /**
  132. * @private
  133. * @type {module:zrender/core/GestureMgr}
  134. */
  135. this._gestureMgr;
  136. Draggable.call(this);
  137. this.setHandlerProxy(proxy);
  138. };
  139. Handler.prototype = {
  140. constructor: Handler,
  141. setHandlerProxy: function (proxy) {
  142. if (this.proxy) {
  143. this.proxy.dispose();
  144. }
  145. if (proxy) {
  146. util.each(handlerNames, function (name) {
  147. proxy.on && proxy.on(name, this[name], this);
  148. }, this); // Attach handler
  149. proxy.handler = this;
  150. }
  151. this.proxy = proxy;
  152. },
  153. mousemove: function (event) {
  154. var x = event.zrX;
  155. var y = event.zrY;
  156. var isOutside = isOutsideBoundary(this, x, y);
  157. var lastHovered = this._hovered;
  158. var lastHoveredTarget = lastHovered.target; // If lastHoveredTarget is removed from zr (detected by '__zr') by some API call
  159. // (like 'setOption' or 'dispatchAction') in event handlers, we should find
  160. // lastHovered again here. Otherwise 'mouseout' can not be triggered normally.
  161. // See #6198.
  162. if (lastHoveredTarget && !lastHoveredTarget.__zr) {
  163. lastHovered = this.findHover(lastHovered.x, lastHovered.y);
  164. lastHoveredTarget = lastHovered.target;
  165. }
  166. var hovered = this._hovered = isOutside ? {
  167. x: x,
  168. y: y
  169. } : this.findHover(x, y);
  170. var hoveredTarget = hovered.target;
  171. var proxy = this.proxy;
  172. proxy.setCursor && proxy.setCursor(hoveredTarget ? hoveredTarget.cursor : 'default'); // Mouse out on previous hovered element
  173. if (lastHoveredTarget && hoveredTarget !== lastHoveredTarget) {
  174. this.dispatchToElement(lastHovered, 'mouseout', event);
  175. } // Mouse moving on one element
  176. this.dispatchToElement(hovered, 'mousemove', event); // Mouse over on a new element
  177. if (hoveredTarget && hoveredTarget !== lastHoveredTarget) {
  178. this.dispatchToElement(hovered, 'mouseover', event);
  179. }
  180. },
  181. mouseout: function (event) {
  182. var eventControl = event.zrEventControl;
  183. var zrIsToLocalDOM = event.zrIsToLocalDOM;
  184. if (eventControl !== 'only_globalout') {
  185. this.dispatchToElement(this._hovered, 'mouseout', event);
  186. }
  187. if (eventControl !== 'no_globalout') {
  188. // FIXME: if the pointer moving from the extra doms to realy "outside",
  189. // the `globalout` should have been triggered. But currently not.
  190. !zrIsToLocalDOM && this.trigger('globalout', {
  191. type: 'globalout',
  192. event: event
  193. });
  194. }
  195. },
  196. /**
  197. * Resize
  198. */
  199. resize: function (event) {
  200. this._hovered = {};
  201. },
  202. /**
  203. * Dispatch event
  204. * @param {string} eventName
  205. * @param {event=} eventArgs
  206. */
  207. dispatch: function (eventName, eventArgs) {
  208. var handler = this[eventName];
  209. handler && handler.call(this, eventArgs);
  210. },
  211. /**
  212. * Dispose
  213. */
  214. dispose: function () {
  215. this.proxy.dispose();
  216. this.storage = this.proxy = this.painter = null;
  217. },
  218. /**
  219. * 设置默认的cursor style
  220. * @param {string} [cursorStyle='default'] 例如 crosshair
  221. */
  222. setCursorStyle: function (cursorStyle) {
  223. var proxy = this.proxy;
  224. proxy.setCursor && proxy.setCursor(cursorStyle);
  225. },
  226. /**
  227. * 事件分发代理
  228. *
  229. * @private
  230. * @param {Object} targetInfo {target, topTarget} 目标图形元素
  231. * @param {string} eventName 事件名称
  232. * @param {Object} event 事件对象
  233. */
  234. dispatchToElement: function (targetInfo, eventName, event) {
  235. targetInfo = targetInfo || {};
  236. var el = targetInfo.target;
  237. if (el && el.silent) {
  238. return;
  239. }
  240. var eventHandler = 'on' + eventName;
  241. var eventPacket = makeEventPacket(eventName, targetInfo, event);
  242. while (el) {
  243. el[eventHandler] && (eventPacket.cancelBubble = el[eventHandler].call(el, eventPacket));
  244. el.trigger(eventName, eventPacket);
  245. el = el.parent;
  246. if (eventPacket.cancelBubble) {
  247. break;
  248. }
  249. }
  250. if (!eventPacket.cancelBubble) {
  251. // 冒泡到顶级 zrender 对象
  252. this.trigger(eventName, eventPacket); // 分发事件到用户自定义层
  253. // 用户有可能在全局 click 事件中 dispose,所以需要判断下 painter 是否存在
  254. this.painter && this.painter.eachOtherLayer(function (layer) {
  255. if (typeof layer[eventHandler] === 'function') {
  256. layer[eventHandler].call(layer, eventPacket);
  257. }
  258. if (layer.trigger) {
  259. layer.trigger(eventName, eventPacket);
  260. }
  261. });
  262. }
  263. },
  264. /**
  265. * @private
  266. * @param {number} x
  267. * @param {number} y
  268. * @param {module:zrender/graphic/Displayable} exclude
  269. * @return {model:zrender/Element}
  270. * @method
  271. */
  272. findHover: function (x, y, exclude) {
  273. var list = this.storage.getDisplayList();
  274. var out = {
  275. x: x,
  276. y: y
  277. };
  278. for (var i = list.length - 1; i >= 0; i--) {
  279. var hoverCheckResult;
  280. if (list[i] !== exclude // getDisplayList may include ignored item in VML mode
  281. && !list[i].ignore && (hoverCheckResult = isHover(list[i], x, y))) {
  282. !out.topTarget && (out.topTarget = list[i]);
  283. if (hoverCheckResult !== SILENT) {
  284. out.target = list[i];
  285. break;
  286. }
  287. }
  288. }
  289. return out;
  290. },
  291. processGesture: function (event, stage) {
  292. if (!this._gestureMgr) {
  293. this._gestureMgr = new GestureMgr();
  294. }
  295. var gestureMgr = this._gestureMgr;
  296. stage === 'start' && gestureMgr.clear();
  297. var gestureInfo = gestureMgr.recognize(event, this.findHover(event.zrX, event.zrY, null).target, this.proxy.dom);
  298. stage === 'end' && gestureMgr.clear(); // Do not do any preventDefault here. Upper application do that if necessary.
  299. if (gestureInfo) {
  300. var type = gestureInfo.type;
  301. event.gestureEvent = type;
  302. this.dispatchToElement({
  303. target: gestureInfo.target
  304. }, type, gestureInfo.event);
  305. }
  306. }
  307. }; // Common handlers
  308. util.each(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  309. Handler.prototype[name] = function (event) {
  310. var x = event.zrX;
  311. var y = event.zrY;
  312. var isOutside = isOutsideBoundary(this, x, y);
  313. var hovered;
  314. var hoveredTarget;
  315. if (name !== 'mouseup' || !isOutside) {
  316. // Find hover again to avoid click event is dispatched manually. Or click is triggered without mouseover
  317. hovered = this.findHover(x, y);
  318. hoveredTarget = hovered.target;
  319. }
  320. if (name === 'mousedown') {
  321. this._downEl = hoveredTarget;
  322. this._downPoint = [event.zrX, event.zrY]; // In case click triggered before mouseup
  323. this._upEl = hoveredTarget;
  324. } else if (name === 'mouseup') {
  325. this._upEl = hoveredTarget;
  326. } else if (name === 'click') {
  327. if (this._downEl !== this._upEl // Original click event is triggered on the whole canvas element,
  328. // including the case that `mousedown` - `mousemove` - `mouseup`,
  329. // which should be filtered, otherwise it will bring trouble to
  330. // pan and zoom.
  331. || !this._downPoint // Arbitrary value
  332. || vec2.dist(this._downPoint, [event.zrX, event.zrY]) > 4) {
  333. return;
  334. }
  335. this._downPoint = null;
  336. }
  337. this.dispatchToElement(hovered, name, event);
  338. };
  339. });
  340. function isHover(displayable, x, y) {
  341. if (displayable[displayable.rectHover ? 'rectContain' : 'contain'](x, y)) {
  342. var el = displayable;
  343. var isSilent;
  344. while (el) {
  345. // If clipped by ancestor.
  346. // FIXME: If clipPath has neither stroke nor fill,
  347. // el.clipPath.contain(x, y) will always return false.
  348. if (el.clipPath && !el.clipPath.contain(x, y)) {
  349. return false;
  350. }
  351. if (el.silent) {
  352. isSilent = true;
  353. }
  354. el = el.parent;
  355. }
  356. return isSilent ? SILENT : true;
  357. }
  358. return false;
  359. }
  360. /**
  361. * See [Drag outside].
  362. */
  363. function isOutsideBoundary(handlerInstance, x, y) {
  364. var painter = handlerInstance.painter;
  365. return x < 0 || x > painter.getWidth() || y < 0 || y > painter.getHeight();
  366. }
  367. util.mixin(Handler, Eventful);
  368. util.mixin(Handler, Draggable);
  369. var _default = Handler;
  370. module.exports = _default;