graphic.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752
  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 * as pathTool from 'zrender/lib/tool/path.js';
  41. import * as matrix from 'zrender/lib/core/matrix.js';
  42. import * as vector from 'zrender/lib/core/vector.js';
  43. import Path from 'zrender/lib/graphic/Path.js';
  44. import Transformable, { copyTransform } from 'zrender/lib/core/Transformable.js';
  45. import ZRImage from 'zrender/lib/graphic/Image.js';
  46. import Group from 'zrender/lib/graphic/Group.js';
  47. import ZRText from 'zrender/lib/graphic/Text.js';
  48. import Circle from 'zrender/lib/graphic/shape/Circle.js';
  49. import Ellipse from 'zrender/lib/graphic/shape/Ellipse.js';
  50. import Sector from 'zrender/lib/graphic/shape/Sector.js';
  51. import Ring from 'zrender/lib/graphic/shape/Ring.js';
  52. import Polygon from 'zrender/lib/graphic/shape/Polygon.js';
  53. import Polyline from 'zrender/lib/graphic/shape/Polyline.js';
  54. import Rect from 'zrender/lib/graphic/shape/Rect.js';
  55. import Line from 'zrender/lib/graphic/shape/Line.js';
  56. import BezierCurve from 'zrender/lib/graphic/shape/BezierCurve.js';
  57. import Arc from 'zrender/lib/graphic/shape/Arc.js';
  58. import CompoundPath from 'zrender/lib/graphic/CompoundPath.js';
  59. import LinearGradient from 'zrender/lib/graphic/LinearGradient.js';
  60. import RadialGradient from 'zrender/lib/graphic/RadialGradient.js';
  61. import BoundingRect from 'zrender/lib/core/BoundingRect.js';
  62. import OrientedBoundingRect from 'zrender/lib/core/OrientedBoundingRect.js';
  63. import Point from 'zrender/lib/core/Point.js';
  64. import IncrementalDisplayable from 'zrender/lib/graphic/IncrementalDisplayable.js';
  65. import * as subPixelOptimizeUtil from 'zrender/lib/graphic/helper/subPixelOptimize.js';
  66. import { extend, isArrayLike, map, defaults, isString, keys, each, hasOwn, isArray, isNumber, clone, assert } from 'zrender/lib/core/util.js';
  67. import { getECData } from './innerStore.js';
  68. import { updateProps, initProps, removeElement, removeElementWithFadeOut, isElementRemoved } from '../animation/basicTransition.js';
  69. import { mathMin, mathMax, mathAbs } from './number.js';
  70. /**
  71. * @deprecated export for compatitable reason
  72. */
  73. export { updateProps, initProps, removeElement, removeElementWithFadeOut, isElementRemoved };
  74. var _customShapeMap = {};
  75. export var XY = ['x', 'y'];
  76. export var WH = ['width', 'height'];
  77. /**
  78. * NOTICE: Only canvas renderer can set these hoverLayer flags.
  79. * @see ElementCommonState['hoverLayer']
  80. */
  81. export var HOVER_LAYER_NO = 0;
  82. export var HOVER_LAYER_FROM_THRESHOLD = 1;
  83. export var HOVER_LAYER_FOR_INCREMENTAL = 2;
  84. /**
  85. * Extend shape with parameters
  86. */
  87. export function extendShape(opts) {
  88. return Path.extend(opts);
  89. }
  90. var extendPathFromString = pathTool.extendFromString;
  91. /**
  92. * Extend path
  93. */
  94. export function extendPath(pathData, opts) {
  95. return extendPathFromString(pathData, opts);
  96. }
  97. /**
  98. * Register a user defined shape.
  99. * The shape class can be fetched by `getShapeClass`
  100. * This method will overwrite the registered shapes, including
  101. * the registered built-in shapes, if using the same `name`.
  102. * The shape can be used in `custom series` and
  103. * `graphic component` by declaring `{type: name}`.
  104. *
  105. * @param name
  106. * @param ShapeClass Can be generated by `extendShape`.
  107. */
  108. export function registerShape(name, ShapeClass) {
  109. _customShapeMap[name] = ShapeClass;
  110. }
  111. /**
  112. * Find shape class registered by `registerShape`. Usually used in
  113. * fetching user defined shape.
  114. *
  115. * [Caution]:
  116. * (1) This method **MUST NOT be used inside echarts !!!**, unless it is prepared
  117. * to use user registered shapes.
  118. * Because the built-in shape (see `getBuiltInShape`) will be registered by
  119. * `registerShape` by default. That enables users to get both built-in
  120. * shapes as well as the shapes belonging to themsleves. But users can overwrite
  121. * the built-in shapes by using names like 'circle', 'rect' via calling
  122. * `registerShape`. So the echarts inner featrues should not fetch shapes from here
  123. * in case that it is overwritten by users, except that some features, like
  124. * `custom series`, `graphic component`, do it deliberately.
  125. *
  126. * (2) In the features like `custom series`, `graphic component`, the user input
  127. * `{tpye: 'xxx'}` does not only specify shapes but also specify other graphic
  128. * elements like `'group'`, `'text'`, `'image'` or event `'path'`. Those names
  129. * are reserved names, that is, if some user registers a shape named `'image'`,
  130. * the shape will not be used. If we intending to add some more reserved names
  131. * in feature, that might bring break changes (disable some existing user shape
  132. * names). But that case probably rarely happens. So we don't make more mechanism
  133. * to resolve this issue here.
  134. *
  135. * @param name
  136. * @return The shape class. If not found, return nothing.
  137. */
  138. export function getShapeClass(name) {
  139. if (_customShapeMap.hasOwnProperty(name)) {
  140. return _customShapeMap[name];
  141. }
  142. }
  143. /**
  144. * Create a path element from path data string
  145. * @param pathData
  146. * @param opts
  147. * @param rect
  148. * @param layout 'center' or 'cover' default to be cover
  149. */
  150. export function makePath(pathData, opts, rect, layout) {
  151. var path = pathTool.createFromString(pathData, opts);
  152. if (rect) {
  153. if (layout === 'center') {
  154. rect = centerGraphic(rect, path.getBoundingRect());
  155. }
  156. resizePath(path, rect);
  157. }
  158. return path;
  159. }
  160. /**
  161. * Create a image element from image url
  162. * @param imageUrl image url
  163. * @param opts options
  164. * @param rect constrain rect
  165. * @param layout 'center' or 'cover'. Default to be 'cover'
  166. */
  167. export function makeImage(imageUrl, rect, layout) {
  168. var zrImg = new ZRImage({
  169. style: {
  170. image: imageUrl,
  171. x: rect.x,
  172. y: rect.y,
  173. width: rect.width,
  174. height: rect.height
  175. },
  176. onload: function (img) {
  177. if (layout === 'center') {
  178. var boundingRect = {
  179. width: img.width,
  180. height: img.height
  181. };
  182. zrImg.setStyle(centerGraphic(rect, boundingRect));
  183. }
  184. }
  185. });
  186. return zrImg;
  187. }
  188. /**
  189. * Get position of centered element in bounding box.
  190. *
  191. * @param rect element local bounding box
  192. * @param boundingRect constraint bounding box
  193. * @return element position containing x, y, width, and height
  194. */
  195. function centerGraphic(rect, boundingRect) {
  196. // Set rect to center, keep width / height ratio.
  197. var aspect = boundingRect.width / boundingRect.height;
  198. var width = rect.height * aspect;
  199. var height;
  200. if (width <= rect.width) {
  201. height = rect.height;
  202. } else {
  203. width = rect.width;
  204. height = width / aspect;
  205. }
  206. var cx = rect.x + rect.width / 2;
  207. var cy = rect.y + rect.height / 2;
  208. return {
  209. x: cx - width / 2,
  210. y: cy - height / 2,
  211. width: width,
  212. height: height
  213. };
  214. }
  215. export var mergePath = pathTool.mergePath;
  216. /**
  217. * Resize a path to fit the rect
  218. * @param path
  219. * @param rect
  220. */
  221. export function resizePath(path, rect) {
  222. if (!path.applyTransform) {
  223. return;
  224. }
  225. var pathRect = path.getBoundingRect();
  226. var m = pathRect.calculateTransform(rect);
  227. path.applyTransform(m);
  228. }
  229. /**
  230. * Sub pixel optimize line for canvas
  231. */
  232. export function subPixelOptimizeLine(shape, lineWidth) {
  233. subPixelOptimizeUtil.subPixelOptimizeLine(shape, shape, {
  234. lineWidth: lineWidth
  235. });
  236. return shape;
  237. }
  238. /**
  239. * Sub pixel optimize rect for canvas
  240. */
  241. export function subPixelOptimizeRect(shape, style) {
  242. subPixelOptimizeUtil.subPixelOptimizeRect(shape, shape, style);
  243. return shape;
  244. }
  245. /**
  246. * Sub pixel optimize for canvas
  247. *
  248. * @param position Coordinate, such as x, y
  249. * @param lineWidth Should be nonnegative integer.
  250. * @param positiveOrNegative Default false (negative).
  251. * @return Optimized position.
  252. */
  253. export var subPixelOptimize = subPixelOptimizeUtil.subPixelOptimize;
  254. /**
  255. * Get transform matrix of target (param target),
  256. * in coordinate of its ancestor (param ancestor)
  257. *
  258. * @param target
  259. * @param [ancestor]
  260. */
  261. export function getTransform(target, ancestor) {
  262. var mat = matrix.identity([]);
  263. while (target && target !== ancestor) {
  264. matrix.mul(mat, target.getLocalTransform(), mat);
  265. target = target.parent;
  266. }
  267. return mat;
  268. }
  269. /**
  270. * Apply transform to an vertex.
  271. * @param target [x, y]
  272. * @param transform Can be:
  273. * + Transform matrix: like [1, 0, 0, 1, 0, 0]
  274. * + {position, rotation, scale}, the same as `zrender/Transformable`.
  275. * @param invert Whether use invert matrix.
  276. * @return [x, y]
  277. */
  278. export function applyTransform(target, transform, invert) {
  279. if (transform && !isArrayLike(transform)) {
  280. transform = Transformable.getLocalTransform(transform);
  281. }
  282. if (invert) {
  283. transform = matrix.invert([], transform);
  284. }
  285. return vector.applyTransform([], target, transform);
  286. }
  287. /**
  288. * @param direction 'left' 'right' 'top' 'bottom'
  289. * @param transform Transform matrix: like [1, 0, 0, 1, 0, 0]
  290. * @param invert Whether use invert matrix.
  291. * @return Transformed direction. 'left' 'right' 'top' 'bottom'
  292. */
  293. export function transformDirection(direction, transform, invert) {
  294. // Pick a base, ensure that transform result will not be (0, 0).
  295. var hBase = transform[4] === 0 || transform[5] === 0 || transform[0] === 0 ? 1 : mathAbs(2 * transform[4] / transform[0]);
  296. var vBase = transform[4] === 0 || transform[5] === 0 || transform[2] === 0 ? 1 : mathAbs(2 * transform[4] / transform[2]);
  297. var vertex = [direction === 'left' ? -hBase : direction === 'right' ? hBase : 0, direction === 'top' ? -vBase : direction === 'bottom' ? vBase : 0];
  298. vertex = applyTransform(vertex, transform, invert);
  299. return mathAbs(vertex[0]) > mathAbs(vertex[1]) ? vertex[0] > 0 ? 'right' : 'left' : vertex[1] > 0 ? 'bottom' : 'top';
  300. }
  301. function isNotGroup(el) {
  302. return !el.isGroup;
  303. }
  304. function isPath(el) {
  305. return el.shape != null;
  306. }
  307. /**
  308. * Apply group transition animation from g1 to g2.
  309. * If no animatableModel, no animation.
  310. */
  311. export function groupTransition(g1, g2, animatableModel) {
  312. if (!g1 || !g2) {
  313. return;
  314. }
  315. function getElMap(g) {
  316. var elMap = {};
  317. g.traverse(function (el) {
  318. if (isNotGroup(el) && el.anid) {
  319. elMap[el.anid] = el;
  320. }
  321. });
  322. return elMap;
  323. }
  324. function getAnimatableProps(el) {
  325. var obj = {
  326. x: el.x,
  327. y: el.y,
  328. rotation: el.rotation
  329. };
  330. if (isPath(el)) {
  331. obj.shape = clone(el.shape);
  332. }
  333. return obj;
  334. }
  335. var elMap1 = getElMap(g1);
  336. g2.traverse(function (el) {
  337. if (isNotGroup(el) && el.anid) {
  338. var oldEl = elMap1[el.anid];
  339. if (oldEl) {
  340. var newProp = getAnimatableProps(el);
  341. el.attr(getAnimatableProps(oldEl));
  342. updateProps(el, newProp, animatableModel, getECData(el).dataIndex);
  343. }
  344. }
  345. });
  346. }
  347. export function clipPointsByRect(points, rect) {
  348. // FIXME: This way might be incorrect when graphic clipped by a corner
  349. // and when element has a border.
  350. return map(points, function (point) {
  351. var x = point[0];
  352. x = mathMax(x, rect.x);
  353. x = mathMin(x, rect.x + rect.width);
  354. var y = point[1];
  355. y = mathMax(y, rect.y);
  356. y = mathMin(y, rect.y + rect.height);
  357. return [x, y];
  358. });
  359. }
  360. /**
  361. * Return a new clipped rect. If rect size are negative, return undefined.
  362. */
  363. export function clipRectByRect(targetRect, rect) {
  364. var x = mathMax(targetRect.x, rect.x);
  365. var x2 = mathMin(targetRect.x + targetRect.width, rect.x + rect.width);
  366. var y = mathMax(targetRect.y, rect.y);
  367. var y2 = mathMin(targetRect.y + targetRect.height, rect.y + rect.height);
  368. // If the total rect is cliped, nothing, including the border,
  369. // should be painted. So return undefined.
  370. if (x2 >= x && y2 >= y) {
  371. return {
  372. x: x,
  373. y: y,
  374. width: x2 - x,
  375. height: y2 - y
  376. };
  377. }
  378. }
  379. export function createIcon(iconStr,
  380. // Support 'image://' or 'path://' or direct svg path.
  381. opt, rect) {
  382. var innerOpts = extend({
  383. rectHover: true
  384. }, opt);
  385. var style = innerOpts.style = {
  386. strokeNoScale: true
  387. };
  388. rect = rect || {
  389. x: -1,
  390. y: -1,
  391. width: 2,
  392. height: 2
  393. };
  394. if (iconStr) {
  395. return iconStr.indexOf('image://') === 0 ? (style.image = iconStr.slice(8), defaults(style, rect), new ZRImage(innerOpts)) : makePath(iconStr.replace('path://', ''), innerOpts, rect, 'center');
  396. }
  397. }
  398. /**
  399. * Return `true` if the given line (line `a`) and the given polygon
  400. * are intersect.
  401. * Note that we do not count colinear as intersect here because no
  402. * requirement for that. We could do that if required in future.
  403. */
  404. export function linePolygonIntersect(a1x, a1y, a2x, a2y, points) {
  405. for (var i = 0, p2 = points[points.length - 1]; i < points.length; i++) {
  406. var p = points[i];
  407. if (lineLineIntersect(a1x, a1y, a2x, a2y, p[0], p[1], p2[0], p2[1])) {
  408. return true;
  409. }
  410. p2 = p;
  411. }
  412. }
  413. /**
  414. * Return `true` if the given two lines (line `a` and line `b`)
  415. * are intersect.
  416. * Note that we do not count colinear as intersect here because no
  417. * requirement for that. We could do that if required in future.
  418. */
  419. export function lineLineIntersect(a1x, a1y, a2x, a2y, b1x, b1y, b2x, b2y) {
  420. // let `vec_m` to be `vec_a2 - vec_a1` and `vec_n` to be `vec_b2 - vec_b1`.
  421. var mx = a2x - a1x;
  422. var my = a2y - a1y;
  423. var nx = b2x - b1x;
  424. var ny = b2y - b1y;
  425. // `vec_m` and `vec_n` are parallel iff
  426. // existing `k` such that `vec_m = k · vec_n`, equivalent to `vec_m X vec_n = 0`.
  427. var nmCrossProduct = crossProduct2d(nx, ny, mx, my);
  428. if (nearZero(nmCrossProduct)) {
  429. return false;
  430. }
  431. // `vec_m` and `vec_n` are intersect iff
  432. // existing `p` and `q` in [0, 1] such that `vec_a1 + p * vec_m = vec_b1 + q * vec_n`,
  433. // such that `q = ((vec_a1 - vec_b1) X vec_m) / (vec_n X vec_m)`
  434. // and `p = ((vec_a1 - vec_b1) X vec_n) / (vec_n X vec_m)`.
  435. var b1a1x = a1x - b1x;
  436. var b1a1y = a1y - b1y;
  437. var q = crossProduct2d(b1a1x, b1a1y, mx, my) / nmCrossProduct;
  438. if (q < 0 || q > 1) {
  439. return false;
  440. }
  441. var p = crossProduct2d(b1a1x, b1a1y, nx, ny) / nmCrossProduct;
  442. if (p < 0 || p > 1) {
  443. return false;
  444. }
  445. return true;
  446. }
  447. /**
  448. * Cross product of 2-dimension vector.
  449. */
  450. function crossProduct2d(x1, y1, x2, y2) {
  451. return x1 * y2 - x2 * y1;
  452. }
  453. function nearZero(val) {
  454. return val <= 1e-6 && val >= -1e-6;
  455. }
  456. /**
  457. * NOTE:
  458. * A negative-width/height rect (due to negative margins) is not supported;
  459. * it will be clampped to zero width/height.
  460. * Although negative-width/height rects can be defined reasonably following the
  461. * similar sense in CSS, but they are rarely used, hard to understand and complicated.
  462. *
  463. * @param rect Assume its width/height >= 0 if existing.
  464. * x/y/width/height is allowed to be NaN,
  465. * for the case that only x/width or y/height is intended to be computed.
  466. * @param delta
  467. * If be `number[]`, should be `[top, right, bottom, left]`,
  468. * which can be used in padding or margin case.
  469. * @see `normalizeCssArray` in `util/format.ts`
  470. * If be `number`, it means [delta, delta, delta, delta],
  471. * which can be used in lineWidth (borderWith) case,
  472. * [NOTICE]: commonly pass lineWidth / 2, following the convention that border is
  473. * half inside half outside of the rect.
  474. * @param shrinkOrExpand
  475. * `true` - shrink if `delta[i]` is positive, commmonly used in `padding` case.
  476. * `false` - expand if `delta[i]` is positive, commmonly used in `margin` case. (default)
  477. * @param noNegative
  478. * `true` - negative `delta[i]` will be clampped to 0.
  479. * `false` - No clamp to `delta`. (default).
  480. * @return The input `rect`.
  481. */
  482. export function expandOrShrinkRect(rect, delta, shrinkOrExpand, noNegative, minSize // by default [0, 0].
  483. ) {
  484. if (delta == null) {
  485. return rect;
  486. } else if (isNumber(delta)) {
  487. _tmpExpandRectDelta[0] = _tmpExpandRectDelta[1] = _tmpExpandRectDelta[2] = _tmpExpandRectDelta[3] = delta;
  488. } else {
  489. if (process.env.NODE_ENV !== 'production') {
  490. assert(delta.length === 4);
  491. }
  492. _tmpExpandRectDelta[0] = delta[0];
  493. _tmpExpandRectDelta[1] = delta[1];
  494. _tmpExpandRectDelta[2] = delta[2];
  495. _tmpExpandRectDelta[3] = delta[3];
  496. }
  497. if (noNegative) {
  498. _tmpExpandRectDelta[0] = mathMax(0, _tmpExpandRectDelta[0]);
  499. _tmpExpandRectDelta[1] = mathMax(0, _tmpExpandRectDelta[1]);
  500. _tmpExpandRectDelta[2] = mathMax(0, _tmpExpandRectDelta[2]);
  501. _tmpExpandRectDelta[3] = mathMax(0, _tmpExpandRectDelta[3]);
  502. }
  503. if (shrinkOrExpand) {
  504. _tmpExpandRectDelta[0] = -_tmpExpandRectDelta[0];
  505. _tmpExpandRectDelta[1] = -_tmpExpandRectDelta[1];
  506. _tmpExpandRectDelta[2] = -_tmpExpandRectDelta[2];
  507. _tmpExpandRectDelta[3] = -_tmpExpandRectDelta[3];
  508. }
  509. expandRectOnOneDimension(rect, _tmpExpandRectDelta, 'x', 'width', 3, 1, minSize && minSize[0] || 0);
  510. expandRectOnOneDimension(rect, _tmpExpandRectDelta, 'y', 'height', 0, 2, minSize && minSize[1] || 0);
  511. return rect;
  512. }
  513. var _tmpExpandRectDelta = [0, 0, 0, 0];
  514. function expandRectOnOneDimension(rect, delta, xy, wh, ltIdx, rbIdx, minSize) {
  515. var deltaSum = delta[rbIdx] + delta[ltIdx];
  516. var oldSize = rect[wh];
  517. rect[wh] += deltaSum;
  518. minSize = mathMax(0, mathMin(minSize, oldSize));
  519. if (rect[wh] < minSize) {
  520. rect[wh] = minSize;
  521. // Try to make the position of the zero rect reasonable in most visual cases.
  522. rect[xy] += delta[ltIdx] >= 0 ? -delta[ltIdx] : delta[rbIdx] >= 0 ? oldSize + delta[rbIdx] : mathAbs(deltaSum) > 1e-8 ? (oldSize - minSize) * delta[ltIdx] / deltaSum : 0;
  523. } else {
  524. rect[xy] -= delta[ltIdx];
  525. }
  526. }
  527. export function setTooltipConfig(opt) {
  528. var itemTooltipOption = opt.itemTooltipOption;
  529. var componentModel = opt.componentModel;
  530. var itemName = opt.itemName;
  531. var itemTooltipOptionObj = isString(itemTooltipOption) ? {
  532. formatter: itemTooltipOption
  533. } : itemTooltipOption;
  534. var mainType = componentModel.mainType;
  535. var componentIndex = componentModel.componentIndex;
  536. var formatterParams = {
  537. componentType: mainType,
  538. name: itemName,
  539. $vars: ['name']
  540. };
  541. formatterParams[mainType + 'Index'] = componentIndex;
  542. var formatterParamsExtra = opt.formatterParamsExtra;
  543. if (formatterParamsExtra) {
  544. each(keys(formatterParamsExtra), function (key) {
  545. if (!hasOwn(formatterParams, key)) {
  546. formatterParams[key] = formatterParamsExtra[key];
  547. formatterParams.$vars.push(key);
  548. }
  549. });
  550. }
  551. var ecData = getECData(opt.el);
  552. ecData.componentMainType = mainType;
  553. ecData.componentIndex = componentIndex;
  554. ecData.tooltipConfig = {
  555. name: itemName,
  556. option: defaults({
  557. content: itemName,
  558. encodeHTMLContent: true,
  559. formatterParams: formatterParams
  560. }, itemTooltipOptionObj)
  561. };
  562. }
  563. function traverseElement(el, cb) {
  564. var stopped;
  565. // TODO
  566. // Polyfill for fixing zrender group traverse don't visit it's root issue.
  567. if (el.isGroup) {
  568. stopped = cb(el);
  569. }
  570. if (!stopped) {
  571. el.traverse(cb);
  572. }
  573. }
  574. export function traverseElements(els, cb) {
  575. if (els) {
  576. if (isArray(els)) {
  577. for (var i = 0; i < els.length; i++) {
  578. traverseElement(els[i], cb);
  579. }
  580. } else {
  581. traverseElement(els, cb);
  582. }
  583. }
  584. }
  585. /**
  586. * After a boundingRect applying a `transform`, whether to be still parallel screen X and Y.
  587. */
  588. export function isBoundingRectAxisAligned(transform) {
  589. return !transform || mathAbs(transform[1]) < AXIS_ALIGN_EPSILON && mathAbs(transform[2]) < AXIS_ALIGN_EPSILON || mathAbs(transform[0]) < AXIS_ALIGN_EPSILON && mathAbs(transform[3]) < AXIS_ALIGN_EPSILON;
  590. }
  591. var AXIS_ALIGN_EPSILON = 1e-5;
  592. /**
  593. * Create or copy to the existing bounding rect to avoid modifying `source`.
  594. *
  595. * @usage
  596. * out.rect = ensureCopyRect(out.rect, sourceRect);
  597. */
  598. export function ensureCopyRect(target, source) {
  599. return target ? BoundingRect.copy(target, source) : source.clone();
  600. }
  601. /**
  602. * Create or copy to the existing transform to avoid modifying `source`.
  603. *
  604. * [CAUTION]: transform is `NullUndefined` if no transform, following convention of zrender,
  605. * and enable to bypass some unnecessary calculation, since in most cases there is no transform.
  606. *
  607. * @usage
  608. * out.transform = ensureCopyTransform(out.transform, sourceTransform);
  609. */
  610. export function ensureCopyTransform(target, source) {
  611. return source ? matrix.copy(target || matrix.create(), source) : undefined;
  612. }
  613. export function retrieveZInfo(model) {
  614. return {
  615. z: model.get('z') || 0,
  616. zlevel: model.get('zlevel') || 0
  617. };
  618. }
  619. /**
  620. * Assume all of the elements has the same `z` and `zlevel`.
  621. */
  622. export function calcZ2Range(el) {
  623. var max = -Infinity;
  624. var min = Infinity;
  625. traverseElement(el, function (el) {
  626. visitEl(el);
  627. visitEl(el.getTextContent());
  628. visitEl(el.getTextGuideLine());
  629. });
  630. function visitEl(el) {
  631. if (!el || el.isGroup) {
  632. return;
  633. }
  634. var currentStates = el.currentStates;
  635. if (currentStates.length) {
  636. for (var idx = 0; idx < currentStates.length; idx++) {
  637. calcZ2(el.states[currentStates[idx]]);
  638. }
  639. }
  640. calcZ2(el);
  641. }
  642. function calcZ2(entity) {
  643. if (entity) {
  644. var z2 = entity.z2;
  645. // Consider z2 may be NullUndefined
  646. if (z2 > max) {
  647. max = z2;
  648. }
  649. if (z2 < min) {
  650. min = z2;
  651. }
  652. }
  653. }
  654. if (min > max) {
  655. min = max = 0;
  656. }
  657. return {
  658. min: min,
  659. max: max
  660. };
  661. }
  662. export function traverseUpdateZ(el, z, zlevel) {
  663. doUpdateZ(el, z, zlevel, -Infinity);
  664. }
  665. function doUpdateZ(el, z, zlevel,
  666. // FIXME: Ideally all the labels should be above all the glyphs by default,
  667. // e.g. in graph, edge labels should be above node elements.
  668. // Currently impl does not guarantee that.
  669. maxZ2) {
  670. // `ignoreModelZ` is used to intentionally lift elements to cover other elements,
  671. // where maxZ2 (for label.z2) should also not be counted for its parents.
  672. if (el.ignoreModelZ) {
  673. return maxZ2;
  674. }
  675. // Group may also have textContent
  676. var label = el.getTextContent();
  677. var labelLine = el.getTextGuideLine();
  678. var isGroup = el.isGroup;
  679. if (isGroup) {
  680. // set z & zlevel of children elements of Group
  681. var children = el.childrenRef();
  682. for (var i = 0; i < children.length; i++) {
  683. maxZ2 = mathMax(doUpdateZ(children[i], z, zlevel, maxZ2), maxZ2);
  684. }
  685. } else {
  686. // not Group
  687. el.z = z;
  688. el.zlevel = zlevel;
  689. maxZ2 = mathMax(el.z2 || 0, maxZ2);
  690. }
  691. // NOTICE: Do not call any method that can set REDRAW_BIT,
  692. // otherwise progressive rendering is broken.
  693. // always set z and zlevel if label/labelLine exists
  694. if (label) {
  695. label.z = z;
  696. label.zlevel = zlevel;
  697. // lift z2 of text content
  698. // TODO if el.emphasis.z2 is spcefied, what about textContent.
  699. isFinite(maxZ2) && (label.z2 = maxZ2 + 2);
  700. }
  701. if (labelLine) {
  702. var textGuideLineConfig = el.textGuideLineConfig;
  703. labelLine.z = z;
  704. labelLine.zlevel = zlevel;
  705. isFinite(maxZ2) && (labelLine.z2 = maxZ2 + (textGuideLineConfig && textGuideLineConfig.showAbove ? 1 : -1));
  706. }
  707. return maxZ2;
  708. }
  709. export function payloadDisableAnimation(payload) {
  710. // Disable animation in `updateProps` of `graphic.ts`.
  711. payload.animation = {
  712. duration: 0
  713. };
  714. return payload;
  715. }
  716. /**
  717. * Decompose an affine matrix to
  718. * x/y/scaleX/scaleY/rotation/skewX/skewY
  719. */
  720. export function decomposeTransform(out, mt) {
  721. mt ? matrix.copy(tmpDTR.transform, mt) : matrix.identity(tmpDTR.transform);
  722. // Use a tmp transformable to avoid effects from parent.
  723. tmpDTR.decomposeTransform();
  724. copyTransform(out, tmpDTR);
  725. return out;
  726. }
  727. var tmpDTR = new Transformable();
  728. tmpDTR.transform = matrix.create();
  729. /**
  730. * If not canvas painter, return null/undefined.
  731. */
  732. export function getCurrentCanvasPainter(api) {
  733. var painter = api.getZr().painter;
  734. return painter.getType() === 'canvas' ? painter : null;
  735. }
  736. // Register built-in shapes. These shapes might be overwritten
  737. // by users, although we do not recommend that.
  738. registerShape('circle', Circle);
  739. registerShape('ellipse', Ellipse);
  740. registerShape('sector', Sector);
  741. registerShape('ring', Ring);
  742. registerShape('polygon', Polygon);
  743. registerShape('polyline', Polyline);
  744. registerShape('rect', Rect);
  745. registerShape('line', Line);
  746. registerShape('bezierCurve', BezierCurve);
  747. registerShape('arc', Arc);
  748. export { Group, ZRImage as Image, ZRText as Text, Circle, Ellipse, Sector, Ring, Polygon, Polyline, Rect, Line, BezierCurve, Arc, IncrementalDisplayable, CompoundPath, LinearGradient, RadialGradient, BoundingRect, OrientedBoundingRect, Point, Path };