Handler.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. import * as util from './core/util';
  2. import * as vec2 from './core/vector';
  3. import Draggable from './mixin/Draggable';
  4. import Eventful from './mixin/Eventful';
  5. import * as eventTool from './core/event';
  6. import GestureMgr from './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 = [
  91. 'click', 'dblclick', 'mousewheel', 'mouseout',
  92. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  93. ];
  94. /**
  95. * @alias module:zrender/Handler
  96. * @constructor
  97. * @extends module:zrender/mixin/Eventful
  98. * @param {module:zrender/Storage} storage Storage instance.
  99. * @param {module:zrender/Painter} painter Painter instance.
  100. * @param {module:zrender/dom/HandlerProxy} proxy HandlerProxy instance.
  101. * @param {HTMLElement} painterRoot painter.root (not painter.getViewportRoot()).
  102. */
  103. var Handler = function (storage, painter, proxy, painterRoot) {
  104. Eventful.call(this);
  105. this.storage = storage;
  106. this.painter = painter;
  107. this.painterRoot = painterRoot;
  108. proxy = proxy || new EmptyProxy();
  109. /**
  110. * Proxy of event. can be Dom, WebGLSurface, etc.
  111. */
  112. this.proxy = null;
  113. /**
  114. * {target, topTarget, x, y}
  115. * @private
  116. * @type {Object}
  117. */
  118. this._hovered = {};
  119. /**
  120. * @private
  121. * @type {Date}
  122. */
  123. this._lastTouchMoment;
  124. /**
  125. * @private
  126. * @type {number}
  127. */
  128. this._lastX;
  129. /**
  130. * @private
  131. * @type {number}
  132. */
  133. this._lastY;
  134. /**
  135. * @private
  136. * @type {module:zrender/core/GestureMgr}
  137. */
  138. this._gestureMgr;
  139. Draggable.call(this);
  140. this.setHandlerProxy(proxy);
  141. };
  142. Handler.prototype = {
  143. constructor: Handler,
  144. setHandlerProxy: function (proxy) {
  145. if (this.proxy) {
  146. this.proxy.dispose();
  147. }
  148. if (proxy) {
  149. util.each(handlerNames, function (name) {
  150. proxy.on && proxy.on(name, this[name], this);
  151. }, this);
  152. // Attach handler
  153. proxy.handler = this;
  154. }
  155. this.proxy = proxy;
  156. },
  157. mousemove: function (event) {
  158. var x = event.zrX;
  159. var y = event.zrY;
  160. var isOutside = isOutsideBoundary(this, x, y);
  161. var lastHovered = this._hovered;
  162. var lastHoveredTarget = lastHovered.target;
  163. // If lastHoveredTarget is removed from zr (detected by '__zr') by some API call
  164. // (like 'setOption' or 'dispatchAction') in event handlers, we should find
  165. // lastHovered again here. Otherwise 'mouseout' can not be triggered normally.
  166. // See #6198.
  167. if (lastHoveredTarget && !lastHoveredTarget.__zr) {
  168. lastHovered = this.findHover(lastHovered.x, lastHovered.y);
  169. lastHoveredTarget = lastHovered.target;
  170. }
  171. var hovered = this._hovered = isOutside ? {x: x, y: y} : this.findHover(x, y);
  172. var hoveredTarget = hovered.target;
  173. var proxy = this.proxy;
  174. proxy.setCursor && proxy.setCursor(hoveredTarget ? hoveredTarget.cursor : 'default');
  175. // Mouse out on previous hovered element
  176. if (lastHoveredTarget && hoveredTarget !== lastHoveredTarget) {
  177. this.dispatchToElement(lastHovered, 'mouseout', event);
  178. }
  179. // Mouse moving on one element
  180. this.dispatchToElement(hovered, 'mousemove', event);
  181. // Mouse over on a new element
  182. if (hoveredTarget && hoveredTarget !== lastHoveredTarget) {
  183. this.dispatchToElement(hovered, 'mouseover', event);
  184. }
  185. },
  186. mouseout: function (event) {
  187. var eventControl = event.zrEventControl;
  188. var zrIsToLocalDOM = event.zrIsToLocalDOM;
  189. if (eventControl !== 'only_globalout') {
  190. this.dispatchToElement(this._hovered, 'mouseout', event);
  191. }
  192. if (eventControl !== 'no_globalout') {
  193. // FIXME: if the pointer moving from the extra doms to realy "outside",
  194. // the `globalout` should have been triggered. But currently not.
  195. !zrIsToLocalDOM && this.trigger('globalout', {type: 'globalout', event: event});
  196. }
  197. },
  198. /**
  199. * Resize
  200. */
  201. resize: function (event) {
  202. this._hovered = {};
  203. },
  204. /**
  205. * Dispatch event
  206. * @param {string} eventName
  207. * @param {event=} eventArgs
  208. */
  209. dispatch: function (eventName, eventArgs) {
  210. var handler = this[eventName];
  211. handler && handler.call(this, eventArgs);
  212. },
  213. /**
  214. * Dispose
  215. */
  216. dispose: function () {
  217. this.proxy.dispose();
  218. this.storage =
  219. this.proxy =
  220. this.painter = null;
  221. },
  222. /**
  223. * 设置默认的cursor style
  224. * @param {string} [cursorStyle='default'] 例如 crosshair
  225. */
  226. setCursorStyle: function (cursorStyle) {
  227. var proxy = this.proxy;
  228. proxy.setCursor && proxy.setCursor(cursorStyle);
  229. },
  230. /**
  231. * 事件分发代理
  232. *
  233. * @private
  234. * @param {Object} targetInfo {target, topTarget} 目标图形元素
  235. * @param {string} eventName 事件名称
  236. * @param {Object} event 事件对象
  237. */
  238. dispatchToElement: function (targetInfo, eventName, event) {
  239. targetInfo = targetInfo || {};
  240. var el = targetInfo.target;
  241. if (el && el.silent) {
  242. return;
  243. }
  244. var eventHandler = 'on' + eventName;
  245. var eventPacket = makeEventPacket(eventName, targetInfo, event);
  246. while (el) {
  247. el[eventHandler]
  248. && (eventPacket.cancelBubble = el[eventHandler].call(el, eventPacket));
  249. el.trigger(eventName, eventPacket);
  250. el = el.parent;
  251. if (eventPacket.cancelBubble) {
  252. break;
  253. }
  254. }
  255. if (!eventPacket.cancelBubble) {
  256. // 冒泡到顶级 zrender 对象
  257. this.trigger(eventName, eventPacket);
  258. // 分发事件到用户自定义层
  259. // 用户有可能在全局 click 事件中 dispose,所以需要判断下 painter 是否存在
  260. this.painter && this.painter.eachOtherLayer(function (layer) {
  261. if (typeof (layer[eventHandler]) === 'function') {
  262. layer[eventHandler].call(layer, eventPacket);
  263. }
  264. if (layer.trigger) {
  265. layer.trigger(eventName, eventPacket);
  266. }
  267. });
  268. }
  269. },
  270. /**
  271. * @private
  272. * @param {number} x
  273. * @param {number} y
  274. * @param {module:zrender/graphic/Displayable} exclude
  275. * @return {model:zrender/Element}
  276. * @method
  277. */
  278. findHover: function (x, y, exclude) {
  279. var list = this.storage.getDisplayList();
  280. var out = {x: x, y: y};
  281. for (var i = list.length - 1; i >= 0; i--) {
  282. var hoverCheckResult;
  283. if (list[i] !== exclude
  284. // getDisplayList may include ignored item in VML mode
  285. && !list[i].ignore
  286. && (hoverCheckResult = isHover(list[i], x, y))
  287. ) {
  288. !out.topTarget && (out.topTarget = list[i]);
  289. if (hoverCheckResult !== SILENT) {
  290. out.target = list[i];
  291. break;
  292. }
  293. }
  294. }
  295. return out;
  296. },
  297. processGesture: function (event, stage) {
  298. if (!this._gestureMgr) {
  299. this._gestureMgr = new GestureMgr();
  300. }
  301. var gestureMgr = this._gestureMgr;
  302. stage === 'start' && gestureMgr.clear();
  303. var gestureInfo = gestureMgr.recognize(
  304. event,
  305. this.findHover(event.zrX, event.zrY, null).target,
  306. this.proxy.dom
  307. );
  308. stage === 'end' && gestureMgr.clear();
  309. // Do not do any preventDefault here. Upper application do that if necessary.
  310. if (gestureInfo) {
  311. var type = gestureInfo.type;
  312. event.gestureEvent = type;
  313. this.dispatchToElement({target: gestureInfo.target}, type, gestureInfo.event);
  314. }
  315. }
  316. };
  317. // Common handlers
  318. util.each(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  319. Handler.prototype[name] = function (event) {
  320. var x = event.zrX;
  321. var y = event.zrY;
  322. var isOutside = isOutsideBoundary(this, x, y);
  323. var hovered;
  324. var hoveredTarget;
  325. if (name !== 'mouseup' || !isOutside) {
  326. // Find hover again to avoid click event is dispatched manually. Or click is triggered without mouseover
  327. hovered = this.findHover(x, y);
  328. hoveredTarget = hovered.target;
  329. }
  330. if (name === 'mousedown') {
  331. this._downEl = hoveredTarget;
  332. this._downPoint = [event.zrX, event.zrY];
  333. // In case click triggered before mouseup
  334. this._upEl = hoveredTarget;
  335. }
  336. else if (name === 'mouseup') {
  337. this._upEl = hoveredTarget;
  338. }
  339. else if (name === 'click') {
  340. if (this._downEl !== this._upEl
  341. // Original click event is triggered on the whole canvas element,
  342. // including the case that `mousedown` - `mousemove` - `mouseup`,
  343. // which should be filtered, otherwise it will bring trouble to
  344. // pan and zoom.
  345. || !this._downPoint
  346. // Arbitrary value
  347. || vec2.dist(this._downPoint, [event.zrX, event.zrY]) > 4
  348. ) {
  349. return;
  350. }
  351. this._downPoint = null;
  352. }
  353. this.dispatchToElement(hovered, name, event);
  354. };
  355. });
  356. function isHover(displayable, x, y) {
  357. if (displayable[displayable.rectHover ? 'rectContain' : 'contain'](x, y)) {
  358. var el = displayable;
  359. var isSilent;
  360. while (el) {
  361. // If clipped by ancestor.
  362. // FIXME: If clipPath has neither stroke nor fill,
  363. // el.clipPath.contain(x, y) will always return false.
  364. if (el.clipPath && !el.clipPath.contain(x, y)) {
  365. return false;
  366. }
  367. if (el.silent) {
  368. isSilent = true;
  369. }
  370. el = el.parent;
  371. }
  372. return isSilent ? SILENT : true;
  373. }
  374. return false;
  375. }
  376. /**
  377. * See [Drag outside].
  378. */
  379. function isOutsideBoundary(handlerInstance, x, y) {
  380. var painter = handlerInstance.painter;
  381. return x < 0 || x > painter.getWidth() || y < 0 || y > painter.getHeight();
  382. }
  383. util.mixin(Handler, Eventful);
  384. util.mixin(Handler, Draggable);
  385. export default Handler;