TooltipHTMLContent.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  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 } from 'zrender/lib/core/util.js';
  41. import { normalizeEvent } from 'zrender/lib/core/event.js';
  42. import { transformLocalCoord } 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, onlyFade) {
  85. var transitionCurve = 'cubic-bezier(0.23,1,0.32,1)';
  86. var transitionOption = " " + duration / 2 + "s " + transitionCurve;
  87. var transitionText = "opacity" + transitionOption + ",visibility" + transitionOption;
  88. if (!onlyFade) {
  89. transitionOption = " " + duration + "s " + transitionCurve;
  90. transitionText += env.transformSupported ? "," + CSS_TRANSFORM_VENDOR + transitionOption : ",left" + transitionOption + ",top" + transitionOption;
  91. }
  92. return CSS_TRANSITION_VENDOR + ':' + transitionText;
  93. }
  94. function assembleTransform(x, y, toString) {
  95. // If using float on style, the final width of the dom might
  96. // keep changing slightly while mouse move. So `toFixed(0)` them.
  97. var x0 = x.toFixed(0) + 'px';
  98. var y0 = y.toFixed(0) + 'px';
  99. // not support transform, use `left` and `top` instead.
  100. if (!env.transformSupported) {
  101. return toString ? "top:" + y0 + ";left:" + x0 + ";" : [['top', y0], ['left', x0]];
  102. }
  103. // support transform
  104. var is3d = env.transform3dSupported;
  105. var translate = "translate" + (is3d ? '3d' : '') + "(" + x0 + "," + y0 + (is3d ? ',0' : '') + ")";
  106. return toString ? 'top:0;left:0;' + CSS_TRANSFORM_VENDOR + ':' + translate + ';' : [['top', 0], ['left', 0], [TRANSFORM_VENDOR, translate]];
  107. }
  108. /**
  109. * @param {Object} textStyle
  110. * @return {string}
  111. * @inner
  112. */
  113. function assembleFont(textStyleModel) {
  114. var cssText = [];
  115. var fontSize = textStyleModel.get('fontSize');
  116. var color = textStyleModel.getTextColor();
  117. color && cssText.push('color:' + color);
  118. cssText.push('font:' + textStyleModel.getFont());
  119. fontSize
  120. // @ts-ignore, leave it to the tooltip refactor.
  121. && cssText.push('line-height:' + Math.round(fontSize * 3 / 2) + 'px');
  122. var shadowColor = textStyleModel.get('textShadowColor');
  123. var shadowBlur = textStyleModel.get('textShadowBlur') || 0;
  124. var shadowOffsetX = textStyleModel.get('textShadowOffsetX') || 0;
  125. var shadowOffsetY = textStyleModel.get('textShadowOffsetY') || 0;
  126. shadowColor && shadowBlur && cssText.push('text-shadow:' + shadowOffsetX + 'px ' + shadowOffsetY + 'px ' + shadowBlur + 'px ' + shadowColor);
  127. each(['decoration', 'align'], function (name) {
  128. var val = textStyleModel.get(name);
  129. val && cssText.push('text-' + name + ':' + val);
  130. });
  131. return cssText.join(';');
  132. }
  133. function assembleCssText(tooltipModel, enableTransition, onlyFade) {
  134. var cssText = [];
  135. var transitionDuration = tooltipModel.get('transitionDuration');
  136. var backgroundColor = tooltipModel.get('backgroundColor');
  137. var shadowBlur = tooltipModel.get('shadowBlur');
  138. var shadowColor = tooltipModel.get('shadowColor');
  139. var shadowOffsetX = tooltipModel.get('shadowOffsetX');
  140. var shadowOffsetY = tooltipModel.get('shadowOffsetY');
  141. var textStyleModel = tooltipModel.getModel('textStyle');
  142. var padding = getPaddingFromTooltipModel(tooltipModel, 'html');
  143. var boxShadow = shadowOffsetX + "px " + shadowOffsetY + "px " + shadowBlur + "px " + shadowColor;
  144. cssText.push('box-shadow:' + boxShadow);
  145. // Animation transition. Do not animate when transitionDuration is 0.
  146. enableTransition && transitionDuration && cssText.push(assembleTransition(transitionDuration, onlyFade));
  147. if (backgroundColor) {
  148. cssText.push('background-color:' + backgroundColor);
  149. }
  150. // Border style
  151. each(['width', 'color', 'radius'], function (name) {
  152. var borderName = 'border-' + name;
  153. var camelCase = toCamelCase(borderName);
  154. var val = tooltipModel.get(camelCase);
  155. val != null && cssText.push(borderName + ':' + val + (name === 'color' ? '' : 'px'));
  156. });
  157. // Text style
  158. cssText.push(assembleFont(textStyleModel));
  159. // Padding
  160. if (padding != null) {
  161. cssText.push('padding:' + normalizeCssArray(padding).join('px ') + 'px');
  162. }
  163. return cssText.join(';') + ';';
  164. }
  165. // If not able to make, do not modify the input `out`.
  166. function makeStyleCoord(out, zr, container, zrX, zrY) {
  167. var zrPainter = zr && zr.painter;
  168. if (container) {
  169. var zrViewportRoot = zrPainter && zrPainter.getViewportRoot();
  170. if (zrViewportRoot) {
  171. // Some APPs might use scale on body, so we support CSS transform here.
  172. transformLocalCoord(out, zrViewportRoot, container, zrX, zrY);
  173. }
  174. } else {
  175. out[0] = zrX;
  176. out[1] = zrY;
  177. // xy should be based on canvas root. But tooltipContent is
  178. // the sibling of canvas root. So padding of ec container
  179. // should be considered here.
  180. var viewportRootOffset = zrPainter && zrPainter.getViewportRootOffset();
  181. if (viewportRootOffset) {
  182. out[0] += viewportRootOffset.offsetLeft;
  183. out[1] += viewportRootOffset.offsetTop;
  184. }
  185. }
  186. out[2] = out[0] / zr.getWidth();
  187. out[3] = out[1] / zr.getHeight();
  188. }
  189. var TooltipHTMLContent = /** @class */function () {
  190. function TooltipHTMLContent(api, opt) {
  191. this._show = false;
  192. this._styleCoord = [0, 0, 0, 0];
  193. this._enterable = true;
  194. this._alwaysShowContent = false;
  195. this._firstShow = true;
  196. this._longHide = true;
  197. if (env.wxa) {
  198. return null;
  199. }
  200. var el = document.createElement('div');
  201. // TODO: TYPE
  202. el.domBelongToZr = true;
  203. this.el = el;
  204. var zr = this._zr = api.getZr();
  205. var appendTo = opt.appendTo;
  206. var container = appendTo && (isString(appendTo) ? document.querySelector(appendTo) : isDom(appendTo) ? appendTo : isFunction(appendTo) && appendTo(api.getDom()));
  207. makeStyleCoord(this._styleCoord, zr, container, api.getWidth() / 2, api.getHeight() / 2);
  208. (container || api.getDom()).appendChild(el);
  209. this._api = api;
  210. this._container = container;
  211. // FIXME
  212. // Is it needed to trigger zr event manually if
  213. // the browser do not support `pointer-events: none`.
  214. var self = this;
  215. el.onmouseenter = function () {
  216. // clear the timeout in hideLater and keep showing tooltip
  217. if (self._enterable) {
  218. clearTimeout(self._hideTimeout);
  219. self._show = true;
  220. }
  221. self._inContent = true;
  222. };
  223. el.onmousemove = function (e) {
  224. e = e || window.event;
  225. if (!self._enterable) {
  226. // `pointer-events: none` is set to tooltip content div
  227. // if `enterable` is set as `false`, and `el.onmousemove`
  228. // can not be triggered. But in browser that do not
  229. // support `pointer-events`, we need to do this:
  230. // Try trigger zrender event to avoid mouse
  231. // in and out shape too frequently
  232. var handler = zr.handler;
  233. var zrViewportRoot = zr.painter.getViewportRoot();
  234. normalizeEvent(zrViewportRoot, e, true);
  235. handler.dispatch('mousemove', e);
  236. }
  237. };
  238. el.onmouseleave = function () {
  239. // set `_inContent` to `false` before `hideLater`
  240. self._inContent = false;
  241. if (self._enterable) {
  242. if (self._show) {
  243. self.hideLater(self._hideDelay);
  244. }
  245. }
  246. };
  247. }
  248. /**
  249. * Update when tooltip is rendered
  250. */
  251. TooltipHTMLContent.prototype.update = function (tooltipModel) {
  252. // FIXME
  253. // Move this logic to ec main?
  254. if (!this._container) {
  255. var container = this._api.getDom();
  256. var position = getComputedStyle(container, 'position');
  257. var domStyle = container.style;
  258. if (domStyle.position !== 'absolute' && position !== 'absolute') {
  259. domStyle.position = 'relative';
  260. }
  261. }
  262. // move tooltip if chart resized
  263. var alwaysShowContent = tooltipModel.get('alwaysShowContent');
  264. alwaysShowContent && this._moveIfResized();
  265. // update alwaysShowContent
  266. this._alwaysShowContent = alwaysShowContent;
  267. // update className
  268. this.el.className = tooltipModel.get('className') || '';
  269. // Hide the tooltip
  270. // PENDING
  271. // this.hide();
  272. };
  273. TooltipHTMLContent.prototype.show = function (tooltipModel, nearPointColor) {
  274. clearTimeout(this._hideTimeout);
  275. clearTimeout(this._longHideTimeout);
  276. var el = this.el;
  277. var style = el.style;
  278. var styleCoord = this._styleCoord;
  279. if (!el.innerHTML) {
  280. style.display = 'none';
  281. } else {
  282. style.cssText = gCssText + assembleCssText(tooltipModel, !this._firstShow, this._longHide)
  283. // initial transform
  284. + assembleTransform(styleCoord[0], styleCoord[1], true) + ("border-color:" + convertToColorString(nearPointColor) + ";") + (tooltipModel.get('extraCssText') || '')
  285. // If mouse occasionally move over the tooltip, a mouseout event will be
  286. // triggered by canvas, and cause some unexpectable result like dragging
  287. // stop, "unfocusAdjacency". Here `pointer-events: none` is used to solve
  288. // it. Although it is not supported by IE8~IE10, fortunately it is a rare
  289. // scenario.
  290. + (";pointer-events:" + (this._enterable ? 'auto' : 'none'));
  291. }
  292. this._show = true;
  293. this._firstShow = false;
  294. this._longHide = false;
  295. };
  296. TooltipHTMLContent.prototype.setContent = function (content, markers, tooltipModel, borderColor, arrowPosition) {
  297. var el = this.el;
  298. if (content == null) {
  299. el.innerHTML = '';
  300. return;
  301. }
  302. var arrow = '';
  303. if (isString(arrowPosition) && tooltipModel.get('trigger') === 'item' && !shouldTooltipConfine(tooltipModel)) {
  304. arrow = assembleArrow(tooltipModel, borderColor, arrowPosition);
  305. }
  306. if (isString(content)) {
  307. el.innerHTML = content + arrow;
  308. } else if (content) {
  309. // Clear previous
  310. el.innerHTML = '';
  311. if (!isArray(content)) {
  312. content = [content];
  313. }
  314. for (var i = 0; i < content.length; i++) {
  315. if (isDom(content[i]) && content[i].parentNode !== el) {
  316. el.appendChild(content[i]);
  317. }
  318. }
  319. // no arrow if empty
  320. if (arrow && el.childNodes.length) {
  321. // no need to create a new parent element, but it's not supported by IE 10 and older.
  322. // const arrowEl = document.createRange().createContextualFragment(arrow);
  323. var arrowEl = document.createElement('div');
  324. arrowEl.innerHTML = arrow;
  325. el.appendChild(arrowEl);
  326. }
  327. }
  328. };
  329. TooltipHTMLContent.prototype.setEnterable = function (enterable) {
  330. this._enterable = enterable;
  331. };
  332. TooltipHTMLContent.prototype.getSize = function () {
  333. var el = this.el;
  334. return [el.offsetWidth, el.offsetHeight];
  335. };
  336. TooltipHTMLContent.prototype.moveTo = function (zrX, zrY) {
  337. var styleCoord = this._styleCoord;
  338. makeStyleCoord(styleCoord, this._zr, this._container, zrX, zrY);
  339. if (styleCoord[0] != null && styleCoord[1] != null) {
  340. var style_1 = this.el.style;
  341. var transforms = assembleTransform(styleCoord[0], styleCoord[1]);
  342. each(transforms, function (transform) {
  343. style_1[transform[0]] = transform[1];
  344. });
  345. }
  346. };
  347. /**
  348. * when `alwaysShowContent` is true,
  349. * move the tooltip after chart resized
  350. */
  351. TooltipHTMLContent.prototype._moveIfResized = function () {
  352. // The ratio of left to width
  353. var ratioX = this._styleCoord[2];
  354. // The ratio of top to height
  355. var ratioY = this._styleCoord[3];
  356. this.moveTo(ratioX * this._zr.getWidth(), ratioY * this._zr.getHeight());
  357. };
  358. TooltipHTMLContent.prototype.hide = function () {
  359. var _this = this;
  360. var style = this.el.style;
  361. style.visibility = 'hidden';
  362. style.opacity = '0';
  363. env.transform3dSupported && (style.willChange = '');
  364. this._show = false;
  365. this._longHideTimeout = setTimeout(function () {
  366. return _this._longHide = true;
  367. }, 500);
  368. };
  369. TooltipHTMLContent.prototype.hideLater = function (time) {
  370. if (this._show && !(this._inContent && this._enterable) && !this._alwaysShowContent) {
  371. if (time) {
  372. this._hideDelay = time;
  373. // Set show false to avoid invoke hideLater multiple times
  374. this._show = false;
  375. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  376. } else {
  377. this.hide();
  378. }
  379. }
  380. };
  381. TooltipHTMLContent.prototype.isShow = function () {
  382. return this._show;
  383. };
  384. TooltipHTMLContent.prototype.dispose = function () {
  385. clearTimeout(this._hideTimeout);
  386. clearTimeout(this._longHideTimeout);
  387. var parentNode = this.el.parentNode;
  388. parentNode && parentNode.removeChild(this.el);
  389. this.el = this._container = null;
  390. };
  391. return TooltipHTMLContent;
  392. }();
  393. export default TooltipHTMLContent;