Handler.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. import * as util from './core/util';
  2. import * as vec2 from './core/vector';
  3. import Draggable from './mixin/Draggable';
  4. import Eventful from './core/Eventful';
  5. import * as eventTool from './core/event';
  6. import {GestureMgr} from './core/GestureMgr';
  7. import Displayable from './graphic/Displayable';
  8. import {PainterBase} from './PainterBase';
  9. import HandlerDomProxy, { HandlerProxyInterface } from './dom/HandlerProxy';
  10. import { ZRRawEvent, ZRPinchEvent, ElementEventName, ElementEventNameWithOn, ZRRawTouchEvent } from './core/types';
  11. import Storage from './Storage';
  12. import Element, {ElementEvent} from './Element';
  13. import CanvasPainter from './canvas/Painter';
  14. import BoundingRect from './core/BoundingRect';
  15. /**
  16. * [The interface between `Handler` and `HandlerProxy`]:
  17. *
  18. * The default `HandlerProxy` only support the common standard web environment
  19. * (e.g., standalone browser, headless browser, embed browser in mobild APP, ...).
  20. * But `HandlerProxy` can be replaced to support more non-standard environment
  21. * (e.g., mini app), or to support more feature that the default `HandlerProxy`
  22. * not provided (like echarts-gl did).
  23. * So the interface between `Handler` and `HandlerProxy` should be stable. Do not
  24. * make break changes util inevitable. The interface include the public methods
  25. * of `Handler` and the events listed in `handlerNames` below, by which `HandlerProxy`
  26. * drives `Handler`.
  27. */
  28. /**
  29. * [DRAG_OUTSIDE]:
  30. *
  31. * That is, triggering `mousemove` and `mouseup` event when the pointer is out of the
  32. * zrender area when dragging. That is important for the improvement of the user experience
  33. * when dragging something near the boundary without being terminated unexpectedly.
  34. *
  35. * We originally consider to introduce new events like `pagemovemove` and `pagemouseup`
  36. * to resolve this issue. But some drawbacks of it is described in
  37. * https://github.com/ecomfe/zrender/pull/536#issuecomment-560286899
  38. *
  39. * Instead, we referenced the specifications:
  40. * https://www.w3.org/TR/touch-events/#the-touchmove-event
  41. * https://www.w3.org/TR/2014/WD-DOM-Level-3-Events-20140925/#event-type-mousemove
  42. * where the the mousemove/touchmove can be continue to fire if the user began a drag
  43. * operation and the pointer has left the boundary. (for the mouse event, browsers
  44. * only do it on `document` and when the pointer has left the boundary of the browser.)
  45. *
  46. * So the default `HandlerProxy` supports this feature similarly: if it is in the dragging
  47. * state (see `pointerCapture` in `HandlerProxy`), the `mousemove` and `mouseup` continue
  48. * to fire until release the pointer. That is implemented by listen to those event on
  49. * `document`.
  50. * If we implement some other `HandlerProxy` only for touch device, that would be easier.
  51. * The touch event support this feature by default.
  52. * The term "pointer capture" is from the spec:
  53. * https://www.w3.org/TR/pointerevents2/#idl-def-element-setpointercapture-pointerid
  54. *
  55. * Note:
  56. * There might be some cases that the mouse event can not be received on `document`.
  57. * For example,
  58. * (A) When `useCapture` is not supported and some user defined event listeners on the ancestor
  59. * of zr dom throw Error.
  60. * (B) When `useCapture` is not supported and some user defined event listeners on the ancestor of
  61. * zr dom call `stopPropagation`.
  62. * In these cases, the `mousemove` event might be keep triggering event when the mouse is released.
  63. * We try to reduce the side-effect in those cases, that is, use `isOutsideBoundary` to prevent
  64. * it from do anything (especially, `findHover`).
  65. * (`useCapture` mean, `addEvnetListener(listener, {capture: true})`, althought it may not be
  66. * suppported in some environments.)
  67. *
  68. * Note:
  69. * If `HandlerProxy` listens to `document` with `useCapture`, `HandlerProxy` needs to
  70. * prevent user-registered-handler from calling `stopPropagation` and `preventDefault`
  71. * when the `event.target` is not a zrender dom element. Otherwise the user-registered-handler
  72. * may be able to prevent other elements (that not relevant to zrender) in the web page from receiving
  73. * dom events.
  74. */
  75. const SILENT = 'silent';
  76. function makeEventPacket(eveType: ElementEventName, targetInfo: {
  77. target?: Element
  78. topTarget?: Element
  79. }, event: ZRRawEvent): ElementEvent {
  80. return {
  81. type: eveType,
  82. event: event,
  83. // target can only be an element that is not silent.
  84. target: targetInfo.target,
  85. // topTarget can be a silent element.
  86. topTarget: targetInfo.topTarget,
  87. cancelBubble: false,
  88. offsetX: event.zrX,
  89. offsetY: event.zrY,
  90. gestureEvent: (event as ZRPinchEvent).gestureEvent,
  91. pinchX: (event as ZRPinchEvent).pinchX,
  92. pinchY: (event as ZRPinchEvent).pinchY,
  93. pinchScale: (event as ZRPinchEvent).pinchScale,
  94. wheelDelta: event.zrDelta,
  95. zrByTouch: event.zrByTouch,
  96. which: event.which,
  97. stop: stopEvent
  98. };
  99. }
  100. function stopEvent(this: ElementEvent) {
  101. eventTool.stop(this.event);
  102. }
  103. class EmptyProxy extends Eventful {
  104. handler: Handler = null
  105. dispose() {}
  106. setCursor() {}
  107. }
  108. class HoveredResult {
  109. x: number
  110. y: number
  111. target: Displayable
  112. topTarget: Displayable
  113. constructor(x?: number, y?: number) {
  114. this.x = x;
  115. this.y = y;
  116. }
  117. }
  118. const handlerNames = [
  119. 'click', 'dblclick', 'mousewheel', 'mouseout',
  120. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  121. ];
  122. type HandlerName = 'click' |'dblclick' |'mousewheel' |'mouseout' |
  123. 'mouseup' |'mousedown' |'mousemove' |'contextmenu';
  124. const tmpRect = new BoundingRect(0, 0, 0, 0);
  125. // TODO draggable
  126. class Handler extends Eventful {
  127. storage: Storage
  128. painter: PainterBase
  129. painterRoot: HTMLElement
  130. proxy: HandlerProxyInterface
  131. private _hovered = new HoveredResult(0, 0)
  132. private _gestureMgr: GestureMgr
  133. private _draggingMgr: Draggable
  134. private _pointerSize: number
  135. _downEl: Element
  136. _upEl: Element
  137. _downPoint: [number, number]
  138. constructor(
  139. storage: Storage,
  140. painter: PainterBase,
  141. proxy: HandlerProxyInterface,
  142. painterRoot: HTMLElement,
  143. pointerSize: number
  144. ) {
  145. super();
  146. this.storage = storage;
  147. this.painter = painter;
  148. this.painterRoot = painterRoot;
  149. this._pointerSize = pointerSize;
  150. proxy = proxy || new EmptyProxy();
  151. /**
  152. * Proxy of event. can be Dom, WebGLSurface, etc.
  153. */
  154. this.proxy = null;
  155. this.setHandlerProxy(proxy);
  156. this._draggingMgr = new Draggable(this);
  157. }
  158. setHandlerProxy(proxy: HandlerProxyInterface) {
  159. if (this.proxy) {
  160. this.proxy.dispose();
  161. }
  162. if (proxy) {
  163. util.each(handlerNames, function (name) {
  164. proxy.on && proxy.on(name, this[name as HandlerName], this);
  165. }, this);
  166. // Attach handler
  167. proxy.handler = this;
  168. }
  169. this.proxy = proxy;
  170. }
  171. mousemove(event: ZRRawEvent) {
  172. const x = event.zrX;
  173. const y = event.zrY;
  174. const isOutside = isOutsideBoundary(this, x, y);
  175. let lastHovered = this._hovered;
  176. let lastHoveredTarget = lastHovered.target;
  177. // If lastHoveredTarget is removed from zr (detected by '__zr') by some API call
  178. // (like 'setOption' or 'dispatchAction') in event handlers, we should find
  179. // lastHovered again here. Otherwise 'mouseout' can not be triggered normally.
  180. // See #6198.
  181. if (lastHoveredTarget && !lastHoveredTarget.__zr) {
  182. lastHovered = this.findHover(lastHovered.x, lastHovered.y);
  183. lastHoveredTarget = lastHovered.target;
  184. }
  185. const hovered = this._hovered = isOutside ? new HoveredResult(x, y) : this.findHover(x, y);
  186. const hoveredTarget = hovered.target;
  187. const proxy = this.proxy;
  188. proxy.setCursor && proxy.setCursor(hoveredTarget ? hoveredTarget.cursor : 'default');
  189. // Mouse out on previous hovered element
  190. if (lastHoveredTarget && hoveredTarget !== lastHoveredTarget) {
  191. this.dispatchToElement(lastHovered, 'mouseout', event);
  192. }
  193. // Mouse moving on one element
  194. this.dispatchToElement(hovered, 'mousemove', event);
  195. // Mouse over on a new element
  196. if (hoveredTarget && hoveredTarget !== lastHoveredTarget) {
  197. this.dispatchToElement(hovered, 'mouseover', event);
  198. }
  199. }
  200. mouseout(event: ZRRawEvent) {
  201. const eventControl = event.zrEventControl;
  202. if (eventControl !== 'only_globalout') {
  203. this.dispatchToElement(this._hovered, 'mouseout', event);
  204. }
  205. if (eventControl !== 'no_globalout') {
  206. // FIXME: if the pointer moving from the extra doms to realy "outside",
  207. // the `globalout` should have been triggered. But currently not.
  208. this.trigger('globalout', {type: 'globalout', event: event});
  209. }
  210. }
  211. /**
  212. * Resize
  213. */
  214. resize() {
  215. this._hovered = new HoveredResult(0, 0);
  216. }
  217. /**
  218. * Dispatch event
  219. */
  220. dispatch(eventName: HandlerName, eventArgs?: any) {
  221. const handler = this[eventName];
  222. handler && handler.call(this, eventArgs);
  223. }
  224. /**
  225. * Dispose
  226. */
  227. dispose() {
  228. this.proxy.dispose();
  229. this.storage = null;
  230. this.proxy = null;
  231. this.painter = null;
  232. }
  233. /**
  234. * 设置默认的cursor style
  235. * @param cursorStyle 例如 crosshair,默认为 'default'
  236. */
  237. setCursorStyle(cursorStyle: string) {
  238. const proxy = this.proxy;
  239. proxy.setCursor && proxy.setCursor(cursorStyle);
  240. }
  241. /**
  242. * 事件分发代理
  243. *
  244. * @private
  245. * @param {Object} targetInfo {target, topTarget} 目标图形元素
  246. * @param {string} eventName 事件名称
  247. * @param {Object} event 事件对象
  248. */
  249. dispatchToElement(targetInfo: {
  250. target?: Element
  251. topTarget?: Element
  252. }, eventName: ElementEventName, event: ZRRawEvent) {
  253. targetInfo = targetInfo || {};
  254. let el = targetInfo.target as Element;
  255. if (el && el.silent) {
  256. return;
  257. }
  258. const eventKey = ('on' + eventName) as ElementEventNameWithOn;
  259. const eventPacket = makeEventPacket(eventName, targetInfo, event);
  260. while (el) {
  261. el[eventKey]
  262. && (eventPacket.cancelBubble = !!el[eventKey].call(el, eventPacket));
  263. el.trigger(eventName, eventPacket);
  264. // Bubble to the host if on the textContent.
  265. // PENDING
  266. el = el.__hostTarget ? el.__hostTarget : el.parent;
  267. if (eventPacket.cancelBubble) {
  268. break;
  269. }
  270. }
  271. if (!eventPacket.cancelBubble) {
  272. // 冒泡到顶级 zrender 对象
  273. this.trigger(eventName, eventPacket);
  274. // 分发事件到用户自定义层
  275. // 用户有可能在全局 click 事件中 dispose,所以需要判断下 painter 是否存在
  276. if (this.painter && (this.painter as CanvasPainter).eachOtherLayer) {
  277. (this.painter as CanvasPainter).eachOtherLayer(function (layer) {
  278. if (typeof (layer[eventKey]) === 'function') {
  279. layer[eventKey].call(layer, eventPacket);
  280. }
  281. if (layer.trigger) {
  282. layer.trigger(eventName, eventPacket);
  283. }
  284. });
  285. }
  286. }
  287. }
  288. findHover(x: number, y: number, exclude?: Displayable): HoveredResult {
  289. const list = this.storage.getDisplayList();
  290. const out = new HoveredResult(x, y);
  291. setHoverTarget(list, out, x, y, exclude);
  292. if (this._pointerSize && !out.target) {
  293. /**
  294. * If no element at pointer position, check intersection with
  295. * elements with pointer enlarged by target size.
  296. */
  297. const candidates: Displayable[] = [];
  298. const pointerSize = this._pointerSize;
  299. const targetSizeHalf = pointerSize / 2;
  300. const pointerRect = new BoundingRect(x - targetSizeHalf, y - targetSizeHalf, pointerSize, pointerSize);
  301. for (let i = list.length - 1; i >= 0; i--) {
  302. const el = list[i];
  303. if (el !== exclude
  304. && !el.ignore
  305. && !el.ignoreCoarsePointer
  306. // If an element ignores, its textContent should also ignore.
  307. // TSpan's parent is not a Group but a ZRText.
  308. // See Text.js _getOrCreateChild
  309. && (!el.parent || !(el.parent as any).ignoreCoarsePointer)
  310. ) {
  311. tmpRect.copy(el.getBoundingRect());
  312. if (el.transform) {
  313. tmpRect.applyTransform(el.transform);
  314. }
  315. if (tmpRect.intersect(pointerRect)) {
  316. candidates.push(el);
  317. }
  318. }
  319. }
  320. /**
  321. * If there are elements whose bounding boxes are near the pointer,
  322. * use the most top one that intersects with the enlarged pointer.
  323. */
  324. if (candidates.length) {
  325. const rStep = 4;
  326. const thetaStep = Math.PI / 12;
  327. const PI2 = Math.PI * 2;
  328. for (let r = 0; r < targetSizeHalf; r += rStep) {
  329. for (let theta = 0; theta < PI2; theta += thetaStep) {
  330. const x1 = x + r * Math.cos(theta);
  331. const y1 = y + r * Math.sin(theta);
  332. setHoverTarget(candidates, out, x1, y1, exclude);
  333. if (out.target) {
  334. return out;
  335. }
  336. }
  337. }
  338. }
  339. }
  340. return out;
  341. }
  342. processGesture(event: ZRRawEvent, stage?: 'start' | 'end' | 'change') {
  343. if (!this._gestureMgr) {
  344. this._gestureMgr = new GestureMgr();
  345. }
  346. const gestureMgr = this._gestureMgr;
  347. stage === 'start' && gestureMgr.clear();
  348. const gestureInfo = gestureMgr.recognize(
  349. event as ZRRawTouchEvent,
  350. this.findHover(event.zrX, event.zrY, null).target,
  351. (this.proxy as HandlerDomProxy).dom
  352. );
  353. stage === 'end' && gestureMgr.clear();
  354. // Do not do any preventDefault here. Upper application do that if necessary.
  355. if (gestureInfo) {
  356. const type = gestureInfo.type;
  357. (event as ZRPinchEvent).gestureEvent = type;
  358. let res = new HoveredResult();
  359. res.target = gestureInfo.target;
  360. this.dispatchToElement(res, type as ElementEventName, gestureInfo.event as ZRRawEvent);
  361. }
  362. }
  363. click: (event: ZRRawEvent) => void
  364. mousedown: (event: ZRRawEvent) => void
  365. mouseup: (event: ZRRawEvent) => void
  366. mousewheel: (event: ZRRawEvent) => void
  367. dblclick: (event: ZRRawEvent) => void
  368. contextmenu: (event: ZRRawEvent) => void
  369. }
  370. // Common handlers
  371. util.each(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name: HandlerName) {
  372. Handler.prototype[name] = function (event) {
  373. const x = event.zrX;
  374. const y = event.zrY;
  375. const isOutside = isOutsideBoundary(this, x, y);
  376. let hovered;
  377. let hoveredTarget;
  378. if (name !== 'mouseup' || !isOutside) {
  379. // Find hover again to avoid click event is dispatched manually. Or click is triggered without mouseover
  380. hovered = this.findHover(x, y);
  381. hoveredTarget = hovered.target;
  382. }
  383. if (name === 'mousedown') {
  384. this._downEl = hoveredTarget;
  385. this._downPoint = [event.zrX, event.zrY];
  386. // In case click triggered before mouseup
  387. this._upEl = hoveredTarget;
  388. }
  389. else if (name === 'mouseup') {
  390. this._upEl = hoveredTarget;
  391. }
  392. else if (name === 'click') {
  393. if (this._downEl !== this._upEl
  394. // Original click event is triggered on the whole canvas element,
  395. // including the case that `mousedown` - `mousemove` - `mouseup`,
  396. // which should be filtered, otherwise it will bring trouble to
  397. // pan and zoom.
  398. || !this._downPoint
  399. // Arbitrary value
  400. || vec2.dist(this._downPoint, [event.zrX, event.zrY]) > 4
  401. ) {
  402. return;
  403. }
  404. this._downPoint = null;
  405. }
  406. this.dispatchToElement(hovered, name, event);
  407. };
  408. });
  409. function isHover(displayable: Displayable, x: number, y: number) {
  410. if (displayable[displayable.rectHover ? 'rectContain' : 'contain'](x, y)) {
  411. let el: Element = displayable;
  412. let isSilent;
  413. let ignoreClip = false;
  414. while (el) {
  415. // Ignore clip on any ancestors.
  416. if (el.ignoreClip) {
  417. ignoreClip = true;
  418. }
  419. if (!ignoreClip) {
  420. let clipPath = el.getClipPath();
  421. // If clipped by ancestor.
  422. // FIXME: If clipPath has neither stroke nor fill,
  423. // el.clipPath.contain(x, y) will always return false.
  424. if (clipPath && !clipPath.contain(x, y)) {
  425. return false;
  426. }
  427. }
  428. if (el.silent) {
  429. isSilent = true;
  430. }
  431. // Consider when el is textContent, also need to be silent
  432. // if any of its host el and its ancestors is silent.
  433. const hostEl = el.__hostTarget;
  434. el = hostEl ? hostEl : el.parent;
  435. }
  436. return isSilent ? SILENT : true;
  437. }
  438. return false;
  439. }
  440. function setHoverTarget(
  441. list: Displayable[],
  442. out: HoveredResult,
  443. x: number,
  444. y: number,
  445. exclude: Displayable
  446. ) {
  447. for (let i = list.length - 1; i >= 0; i--) {
  448. const el = list[i];
  449. let hoverCheckResult;
  450. if (el !== exclude
  451. // getDisplayList may include ignored item in VML mode
  452. && !el.ignore
  453. && (hoverCheckResult = isHover(el, x, y))
  454. ) {
  455. !out.topTarget && (out.topTarget = el);
  456. if (hoverCheckResult !== SILENT) {
  457. out.target = el;
  458. break;
  459. }
  460. }
  461. }
  462. }
  463. /**
  464. * See [DRAG_OUTSIDE].
  465. */
  466. function isOutsideBoundary(handlerInstance: Handler, x: number, y: number) {
  467. const painter = handlerInstance.painter;
  468. return x < 0 || x > painter.getWidth() || y < 0 || y > painter.getHeight();
  469. }
  470. export default Handler;