TooltipHTMLContent.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one
  3. * or more contributor license agreements. See the NOTICE file
  4. * distributed with this work for additional information
  5. * regarding copyright ownership. The ASF licenses this file
  6. * to you under the Apache License, Version 2.0 (the
  7. * "License"); you may not use this file except in compliance
  8. * with the License. You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing,
  13. * software distributed under the License is distributed on an
  14. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15. * KIND, either express or implied. See the License for the
  16. * specific language governing permissions and limitations
  17. * under the License.
  18. */
  19. /**
  20. * AUTO-GENERATED FILE. DO NOT MODIFY.
  21. */
  22. /*
  23. * Licensed to the Apache Software Foundation (ASF) under one
  24. * or more contributor license agreements. See the NOTICE file
  25. * distributed with this work for additional information
  26. * regarding copyright ownership. The ASF licenses this file
  27. * to you under the Apache License, Version 2.0 (the
  28. * "License"); you may not use this file except in compliance
  29. * with the License. You may obtain a copy of the License at
  30. *
  31. * http://www.apache.org/licenses/LICENSE-2.0
  32. *
  33. * Unless required by applicable law or agreed to in writing,
  34. * software distributed under the License is distributed on an
  35. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36. * KIND, either express or implied. See the License for the
  37. * specific language governing permissions and limitations
  38. * under the License.
  39. */
  40. import { isString, indexOf, each, bind, isFunction, isArray, isDom, retrieve2 } from 'zrender/lib/core/util.js';
  41. import { normalizeEvent } from 'zrender/lib/core/event.js';
  42. import { transformLocalCoord, transformLocalCoordClear } from 'zrender/lib/core/dom.js';
  43. import env from 'zrender/lib/core/env.js';
  44. import { convertToColorString, toCamelCase, normalizeCssArray } from '../../util/format.js';
  45. import { shouldTooltipConfine, toCSSVendorPrefix, getComputedStyle, TRANSFORM_VENDOR, TRANSITION_VENDOR } from './helper.js';
  46. import { getPaddingFromTooltipModel } from './tooltipMarkup.js';
  47. /* global document, window */
  48. var CSS_TRANSITION_VENDOR = toCSSVendorPrefix(TRANSITION_VENDOR, 'transition');
  49. var CSS_TRANSFORM_VENDOR = toCSSVendorPrefix(TRANSFORM_VENDOR, 'transform');
  50. // eslint-disable-next-line
  51. var gCssText = "position:absolute;display:block;border-style:solid;white-space:nowrap;z-index:9999999;" + (env.transform3dSupported ? 'will-change:transform;' : '');
  52. function mirrorPos(pos) {
  53. pos = pos === 'left' ? 'right' : pos === 'right' ? 'left' : pos === 'top' ? 'bottom' : 'top';
  54. return pos;
  55. }
  56. function assembleArrow(tooltipModel, borderColor, arrowPosition) {
  57. if (!isString(arrowPosition) || arrowPosition === 'inside') {
  58. return '';
  59. }
  60. var backgroundColor = tooltipModel.get('backgroundColor');
  61. var borderWidth = tooltipModel.get('borderWidth');
  62. borderColor = convertToColorString(borderColor);
  63. var arrowPos = mirrorPos(arrowPosition);
  64. var arrowSize = Math.max(Math.round(borderWidth) * 1.5, 6);
  65. var positionStyle = '';
  66. var transformStyle = CSS_TRANSFORM_VENDOR + ':';
  67. var rotateDeg;
  68. if (indexOf(['left', 'right'], arrowPos) > -1) {
  69. positionStyle += 'top:50%';
  70. transformStyle += "translateY(-50%) rotate(" + (rotateDeg = arrowPos === 'left' ? -225 : -45) + "deg)";
  71. } else {
  72. positionStyle += 'left:50%';
  73. transformStyle += "translateX(-50%) rotate(" + (rotateDeg = arrowPos === 'top' ? 225 : 45) + "deg)";
  74. }
  75. var rotateRadian = rotateDeg * Math.PI / 180;
  76. var arrowWH = arrowSize + borderWidth;
  77. var rotatedWH = arrowWH * Math.abs(Math.cos(rotateRadian)) + arrowWH * Math.abs(Math.sin(rotateRadian));
  78. var arrowOffset = Math.round(((rotatedWH - Math.SQRT2 * borderWidth) / 2 + Math.SQRT2 * borderWidth - (rotatedWH - arrowWH) / 2) * 100) / 100;
  79. positionStyle += ";" + arrowPos + ":-" + arrowOffset + "px";
  80. var borderStyle = borderColor + " solid " + borderWidth + "px;";
  81. var styleCss = ["position:absolute;width:" + arrowSize + "px;height:" + arrowSize + "px;z-index:-1;", positionStyle + ";" + transformStyle + ";", "border-bottom:" + borderStyle, "border-right:" + borderStyle, "background-color:" + backgroundColor + ";"];
  82. return "<div style=\"" + styleCss.join('') + "\"></div>";
  83. }
  84. function assembleTransition(duration, onlyFadeTransition, enableDisplayTransition) {
  85. var transitionCurve = 'cubic-bezier(0.23,1,0.32,1)';
  86. var transitionOption = '';
  87. var transitionText = '';
  88. if (enableDisplayTransition) {
  89. transitionOption = " " + duration / 2 + "s " + transitionCurve;
  90. transitionText = "opacity" + transitionOption + ",visibility" + transitionOption;
  91. }
  92. if (!onlyFadeTransition) {
  93. transitionOption = " " + duration + "s " + transitionCurve;
  94. transitionText += (transitionText.length ? ',' : '') + (env.transformSupported ? "" + CSS_TRANSFORM_VENDOR + transitionOption : ",left" + transitionOption + ",top" + transitionOption);
  95. }
  96. return CSS_TRANSITION_VENDOR + ':' + transitionText;
  97. }
  98. function assembleTransform(x, y, toString) {
  99. // If using float on style, the final width of the dom might
  100. // keep changing slightly while mouse move. So `toFixed(0)` them.
  101. var x0 = x.toFixed(0) + 'px';
  102. var y0 = y.toFixed(0) + 'px';
  103. // not support transform, use `left` and `top` instead.
  104. if (!env.transformSupported) {
  105. return toString ? "top:" + y0 + ";left:" + x0 + ";" : [['top', y0], ['left', x0]];
  106. }
  107. // support transform
  108. var is3d = env.transform3dSupported;
  109. var translate = "translate" + (is3d ? '3d' : '') + "(" + x0 + "," + y0 + (is3d ? ',0' : '') + ")";
  110. return toString ? 'top:0;left:0;' + CSS_TRANSFORM_VENDOR + ':' + translate + ';' : [['top', 0], ['left', 0], [TRANSFORM_VENDOR, translate]];
  111. }
  112. /**
  113. * @param {Object} textStyle
  114. * @return {string}
  115. * @inner
  116. */
  117. function assembleFont(textStyleModel) {
  118. var cssText = [];
  119. var fontSize = textStyleModel.get('fontSize');
  120. var color = textStyleModel.getTextColor();
  121. color && cssText.push('color:' + color);
  122. cssText.push('font:' + textStyleModel.getFont());
  123. // @ts-ignore, leave it to the tooltip refactor.
  124. var lineHeight = retrieve2(textStyleModel.get('lineHeight'), Math.round(fontSize * 3 / 2));
  125. fontSize && cssText.push('line-height:' + lineHeight + 'px');
  126. var shadowColor = textStyleModel.get('textShadowColor');
  127. var shadowBlur = textStyleModel.get('textShadowBlur') || 0;
  128. var shadowOffsetX = textStyleModel.get('textShadowOffsetX') || 0;
  129. var shadowOffsetY = textStyleModel.get('textShadowOffsetY') || 0;
  130. shadowColor && shadowBlur && cssText.push('text-shadow:' + shadowOffsetX + 'px ' + shadowOffsetY + 'px ' + shadowBlur + 'px ' + shadowColor);
  131. each(['decoration', 'align'], function (name) {
  132. var val = textStyleModel.get(name);
  133. val && cssText.push('text-' + name + ':' + val);
  134. });
  135. return cssText.join(';');
  136. }
  137. function assembleCssText(tooltipModel, enableTransition, onlyFadeTransition, enableDisplayTransition) {
  138. var cssText = [];
  139. var transitionDuration = tooltipModel.get('transitionDuration');
  140. var backgroundColor = tooltipModel.get('backgroundColor');
  141. var shadowBlur = tooltipModel.get('shadowBlur');
  142. var shadowColor = tooltipModel.get('shadowColor');
  143. var shadowOffsetX = tooltipModel.get('shadowOffsetX');
  144. var shadowOffsetY = tooltipModel.get('shadowOffsetY');
  145. var textStyleModel = tooltipModel.getModel('textStyle');
  146. var padding = getPaddingFromTooltipModel(tooltipModel, 'html');
  147. var boxShadow = shadowOffsetX + "px " + shadowOffsetY + "px " + shadowBlur + "px " + shadowColor;
  148. cssText.push('box-shadow:' + boxShadow);
  149. // Animation transition. Do not animate when transitionDuration <= 0.
  150. enableTransition && transitionDuration > 0 && cssText.push(assembleTransition(transitionDuration, onlyFadeTransition, enableDisplayTransition));
  151. if (backgroundColor) {
  152. cssText.push('background-color:' + backgroundColor);
  153. }
  154. // Border style
  155. each(['width', 'color', 'radius'], function (name) {
  156. var borderName = 'border-' + name;
  157. var camelCase = toCamelCase(borderName);
  158. var val = tooltipModel.get(camelCase);
  159. val != null && cssText.push(borderName + ':' + val + (name === 'color' ? '' : 'px'));
  160. });
  161. // Text style
  162. cssText.push(assembleFont(textStyleModel));
  163. // Padding
  164. if (padding != null) {
  165. cssText.push('padding:' + normalizeCssArray(padding).join('px ') + 'px');
  166. }
  167. return cssText.join(';') + ';';
  168. }
  169. // If not able to make, do not modify the input `out`.
  170. function makeStyleCoord(out, zr, container, zrX, zrY) {
  171. var zrPainter = zr && zr.painter;
  172. if (container) {
  173. var zrViewportRoot = zrPainter && zrPainter.getViewportRoot();
  174. if (zrViewportRoot) {
  175. // Some APPs might use scale on body, so we support CSS transform here.
  176. transformLocalCoord(out, zrViewportRoot, container, zrX, zrY);
  177. }
  178. } else {
  179. out[0] = zrX;
  180. out[1] = zrY;
  181. // xy should be based on canvas root. But tooltipContent is
  182. // the sibling of canvas root. So padding of ec container
  183. // should be considered here.
  184. var viewportRootOffset = zrPainter && zrPainter.getViewportRootOffset();
  185. if (viewportRootOffset) {
  186. out[0] += viewportRootOffset.offsetLeft;
  187. out[1] += viewportRootOffset.offsetTop;
  188. }
  189. }
  190. out[2] = out[0] / zr.getWidth();
  191. out[3] = out[1] / zr.getHeight();
  192. }
  193. var TooltipHTMLContent = /** @class */function () {
  194. function TooltipHTMLContent(api, opt) {
  195. this._show = false;
  196. this._styleCoord = [0, 0, 0, 0];
  197. this._enterable = true;
  198. this._alwaysShowContent = false;
  199. this._firstShow = true;
  200. this._longHide = true;
  201. if (env.wxa) {
  202. return null;
  203. }
  204. var el = document.createElement('div');
  205. // TODO: TYPE
  206. el.domBelongToZr = true;
  207. this.el = el;
  208. var zr = this._zr = api.getZr();
  209. var appendTo = opt.appendTo;
  210. var container = appendTo && (isString(appendTo) ? document.querySelector(appendTo) : isDom(appendTo) ? appendTo : isFunction(appendTo) && appendTo(api.getDom()));
  211. makeStyleCoord(this._styleCoord, zr, container, api.getWidth() / 2, api.getHeight() / 2);
  212. (container || api.getDom()).appendChild(el);
  213. this._api = api;
  214. this._container = container;
  215. // FIXME
  216. // Is it needed to trigger zr event manually if
  217. // the browser do not support `pointer-events: none`.
  218. var self = this;
  219. el.onmouseenter = function () {
  220. // clear the timeout in hideLater and keep showing tooltip
  221. if (self._enterable) {
  222. clearTimeout(self._hideTimeout);
  223. self._show = true;
  224. }
  225. self._inContent = true;
  226. };
  227. el.onmousemove = function (e) {
  228. e = e || window.event;
  229. if (!self._enterable) {
  230. // `pointer-events: none` is set to tooltip content div
  231. // if `enterable` is set as `false`, and `el.onmousemove`
  232. // can not be triggered. But in browser that do not
  233. // support `pointer-events`, we need to do this:
  234. // Try trigger zrender event to avoid mouse
  235. // in and out shape too frequently
  236. var handler = zr.handler;
  237. var zrViewportRoot = zr.painter.getViewportRoot();
  238. normalizeEvent(zrViewportRoot, e, true);
  239. handler.dispatch('mousemove', e);
  240. }
  241. };
  242. el.onmouseleave = function () {
  243. // set `_inContent` to `false` before `hideLater`
  244. self._inContent = false;
  245. if (self._enterable) {
  246. if (self._show) {
  247. self.hideLater(self._hideDelay);
  248. }
  249. }
  250. };
  251. }
  252. /**
  253. * Update when tooltip is rendered
  254. */
  255. TooltipHTMLContent.prototype.update = function (tooltipModel) {
  256. // FIXME
  257. // Move this logic to ec main?
  258. if (!this._container) {
  259. var container = this._api.getDom();
  260. var position = getComputedStyle(container, 'position');
  261. var domStyle = container.style;
  262. if (domStyle.position !== 'absolute' && position !== 'absolute') {
  263. domStyle.position = 'relative';
  264. }
  265. }
  266. // move tooltip if chart resized
  267. var alwaysShowContent = tooltipModel.get('alwaysShowContent');
  268. alwaysShowContent && this._moveIfResized();
  269. // update alwaysShowContent
  270. this._alwaysShowContent = alwaysShowContent;
  271. this._enableDisplayTransition = tooltipModel.get('displayTransition') && tooltipModel.get('transitionDuration') > 0;
  272. // update className
  273. this.el.className = tooltipModel.get('className') || '';
  274. // Hide the tooltip
  275. // PENDING
  276. // this.hide();
  277. };
  278. TooltipHTMLContent.prototype.show = function (tooltipModel, nearPointColor) {
  279. clearTimeout(this._hideTimeout);
  280. clearTimeout(this._longHideTimeout);
  281. var el = this.el;
  282. var style = el.style;
  283. var styleCoord = this._styleCoord;
  284. if (!el.innerHTML) {
  285. style.display = 'none';
  286. } else {
  287. style.cssText = gCssText + assembleCssText(tooltipModel, !this._firstShow, this._longHide, this._enableDisplayTransition)
  288. // initial transform
  289. + assembleTransform(styleCoord[0], styleCoord[1], true) + ("border-color:" + convertToColorString(nearPointColor) + ";") + (tooltipModel.get('extraCssText') || '')
  290. // If mouse occasionally move over the tooltip, a mouseout event will be
  291. // triggered by canvas, and cause some unexpectable result like dragging
  292. // stop, "unfocusAdjacency". Here `pointer-events: none` is used to solve
  293. // it. Although it is not supported by IE8~IE10, fortunately it is a rare
  294. // scenario.
  295. + (";pointer-events:" + (this._enterable ? 'auto' : 'none'));
  296. }
  297. this._show = true;
  298. this._firstShow = false;
  299. this._longHide = false;
  300. };
  301. TooltipHTMLContent.prototype.setContent = function (content, markers, tooltipModel, borderColor, arrowPosition) {
  302. var el = this.el;
  303. if (content == null) {
  304. el.innerHTML = '';
  305. return;
  306. }
  307. var arrow = '';
  308. if (isString(arrowPosition) && tooltipModel.get('trigger') === 'item' && !shouldTooltipConfine(tooltipModel)) {
  309. arrow = assembleArrow(tooltipModel, borderColor, arrowPosition);
  310. }
  311. if (isString(content)) {
  312. el.innerHTML = content + arrow;
  313. } else if (content) {
  314. // Clear previous
  315. el.innerHTML = '';
  316. if (!isArray(content)) {
  317. content = [content];
  318. }
  319. for (var i = 0; i < content.length; i++) {
  320. if (isDom(content[i]) && content[i].parentNode !== el) {
  321. el.appendChild(content[i]);
  322. }
  323. }
  324. // no arrow if empty
  325. if (arrow && el.childNodes.length) {
  326. // no need to create a new parent element, but it's not supported by IE 10 and older.
  327. // const arrowEl = document.createRange().createContextualFragment(arrow);
  328. var arrowEl = document.createElement('div');
  329. arrowEl.innerHTML = arrow;
  330. el.appendChild(arrowEl);
  331. }
  332. }
  333. };
  334. TooltipHTMLContent.prototype.setEnterable = function (enterable) {
  335. this._enterable = enterable;
  336. };
  337. TooltipHTMLContent.prototype.getSize = function () {
  338. var el = this.el;
  339. return el ? [el.offsetWidth, el.offsetHeight] : [0, 0];
  340. };
  341. TooltipHTMLContent.prototype.moveTo = function (zrX, zrY) {
  342. if (!this.el) {
  343. return;
  344. }
  345. var styleCoord = this._styleCoord;
  346. makeStyleCoord(styleCoord, this._zr, this._container, zrX, zrY);
  347. if (styleCoord[0] != null && styleCoord[1] != null) {
  348. var style_1 = this.el.style;
  349. var transforms = assembleTransform(styleCoord[0], styleCoord[1]);
  350. each(transforms, function (transform) {
  351. style_1[transform[0]] = transform[1];
  352. });
  353. }
  354. };
  355. /**
  356. * when `alwaysShowContent` is true,
  357. * move the tooltip after chart resized
  358. */
  359. TooltipHTMLContent.prototype._moveIfResized = function () {
  360. // The ratio of left to width
  361. var ratioX = this._styleCoord[2];
  362. // The ratio of top to height
  363. var ratioY = this._styleCoord[3];
  364. this.moveTo(ratioX * this._zr.getWidth(), ratioY * this._zr.getHeight());
  365. };
  366. TooltipHTMLContent.prototype.hide = function () {
  367. var _this = this;
  368. var style = this.el.style;
  369. if (this._enableDisplayTransition) {
  370. style.visibility = 'hidden';
  371. style.opacity = '0';
  372. } else {
  373. style.display = 'none';
  374. }
  375. env.transform3dSupported && (style.willChange = '');
  376. this._show = false;
  377. this._longHideTimeout = setTimeout(function () {
  378. return _this._longHide = true;
  379. }, 500);
  380. };
  381. TooltipHTMLContent.prototype.hideLater = function (time) {
  382. if (this._show && !(this._inContent && this._enterable) && !this._alwaysShowContent) {
  383. if (time) {
  384. this._hideDelay = time;
  385. // Set show false to avoid invoke hideLater multiple times
  386. this._show = false;
  387. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  388. } else {
  389. this.hide();
  390. }
  391. }
  392. };
  393. TooltipHTMLContent.prototype.isShow = function () {
  394. return this._show;
  395. };
  396. TooltipHTMLContent.prototype.dispose = function () {
  397. clearTimeout(this._hideTimeout);
  398. clearTimeout(this._longHideTimeout);
  399. var zr = this._zr;
  400. transformLocalCoordClear(zr && zr.painter && zr.painter.getViewportRoot(), this._container);
  401. var el = this.el;
  402. if (el) {
  403. el.onmouseenter = el.onmousemove = el.onmouseleave = null;
  404. var parentNode = el.parentNode;
  405. parentNode && parentNode.removeChild(el);
  406. }
  407. this.el = this._container = null;
  408. };
  409. return TooltipHTMLContent;
  410. }();
  411. export default TooltipHTMLContent;