treemapLayout.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  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. /*
  41. * A third-party license is embedded for some of the code in this file:
  42. * The treemap layout implementation was originally copied from
  43. * "d3.js" with some modifications made for this project.
  44. * (See more details in the comment of the method "squarify" below.)
  45. * The use of the source code of this file is also subject to the terms
  46. * and consitions of the license of "d3.js" (BSD-3Clause, see
  47. * </licenses/LICENSE-d3>).
  48. */
  49. import * as zrUtil from 'zrender/lib/core/util.js';
  50. import BoundingRect from 'zrender/lib/core/BoundingRect.js';
  51. import { parsePercent, MAX_SAFE_INTEGER } from '../../util/number.js';
  52. import * as layout from '../../util/layout.js';
  53. import * as helper from '../helper/treeHelper.js';
  54. var mathMax = Math.max;
  55. var mathMin = Math.min;
  56. var retrieveValue = zrUtil.retrieve;
  57. var each = zrUtil.each;
  58. var PATH_BORDER_WIDTH = ['itemStyle', 'borderWidth'];
  59. var PATH_GAP_WIDTH = ['itemStyle', 'gapWidth'];
  60. var PATH_UPPER_LABEL_SHOW = ['upperLabel', 'show'];
  61. var PATH_UPPER_LABEL_HEIGHT = ['upperLabel', 'height'];
  62. ;
  63. /**
  64. * @public
  65. */
  66. export default {
  67. seriesType: 'treemap',
  68. reset: function (seriesModel, ecModel, api, payload) {
  69. // Layout result in each node:
  70. // {x, y, width, height, area, borderWidth}
  71. var ecWidth = api.getWidth();
  72. var ecHeight = api.getHeight();
  73. var seriesOption = seriesModel.option;
  74. var layoutInfo = layout.getLayoutRect(seriesModel.getBoxLayoutParams(), {
  75. width: api.getWidth(),
  76. height: api.getHeight()
  77. });
  78. var size = seriesOption.size || []; // Compatible with ec2.
  79. var containerWidth = parsePercent(retrieveValue(layoutInfo.width, size[0]), ecWidth);
  80. var containerHeight = parsePercent(retrieveValue(layoutInfo.height, size[1]), ecHeight); // Fetch payload info.
  81. var payloadType = payload && payload.type;
  82. var types = ['treemapZoomToNode', 'treemapRootToNode'];
  83. var targetInfo = helper.retrieveTargetInfo(payload, types, seriesModel);
  84. var rootRect = payloadType === 'treemapRender' || payloadType === 'treemapMove' ? payload.rootRect : null;
  85. var viewRoot = seriesModel.getViewRoot();
  86. var viewAbovePath = helper.getPathToRoot(viewRoot);
  87. if (payloadType !== 'treemapMove') {
  88. var rootSize = payloadType === 'treemapZoomToNode' ? estimateRootSize(seriesModel, targetInfo, viewRoot, containerWidth, containerHeight) : rootRect ? [rootRect.width, rootRect.height] : [containerWidth, containerHeight];
  89. var sort_1 = seriesOption.sort;
  90. if (sort_1 && sort_1 !== 'asc' && sort_1 !== 'desc') {
  91. // Default to be desc order.
  92. sort_1 = 'desc';
  93. }
  94. var options = {
  95. squareRatio: seriesOption.squareRatio,
  96. sort: sort_1,
  97. leafDepth: seriesOption.leafDepth
  98. }; // layout should be cleared because using updateView but not update.
  99. viewRoot.hostTree.clearLayouts(); // TODO
  100. // optimize: if out of view clip, do not layout.
  101. // But take care that if do not render node out of view clip,
  102. // how to calculate start po
  103. var viewRootLayout_1 = {
  104. x: 0,
  105. y: 0,
  106. width: rootSize[0],
  107. height: rootSize[1],
  108. area: rootSize[0] * rootSize[1]
  109. };
  110. viewRoot.setLayout(viewRootLayout_1);
  111. squarify(viewRoot, options, false, 0); // Supplement layout.
  112. viewRootLayout_1 = viewRoot.getLayout();
  113. each(viewAbovePath, function (node, index) {
  114. var childValue = (viewAbovePath[index + 1] || viewRoot).getValue();
  115. node.setLayout(zrUtil.extend({
  116. dataExtent: [childValue, childValue],
  117. borderWidth: 0,
  118. upperHeight: 0
  119. }, viewRootLayout_1));
  120. });
  121. }
  122. var treeRoot = seriesModel.getData().tree.root;
  123. treeRoot.setLayout(calculateRootPosition(layoutInfo, rootRect, targetInfo), true);
  124. seriesModel.setLayoutInfo(layoutInfo); // FIXME
  125. // 现在没有clip功能,暂时取ec高宽。
  126. prunning(treeRoot, // Transform to base element coordinate system.
  127. new BoundingRect(-layoutInfo.x, -layoutInfo.y, ecWidth, ecHeight), viewAbovePath, viewRoot, 0);
  128. }
  129. };
  130. /**
  131. * Layout treemap with squarify algorithm.
  132. * The original presentation of this algorithm
  133. * was made by Mark Bruls, Kees Huizing, and Jarke J. van Wijk
  134. * <https://graphics.ethz.ch/teaching/scivis_common/Literature/squarifiedTreeMaps.pdf>.
  135. * The implementation of this algorithm was originally copied from "d3.js"
  136. * <https://github.com/d3/d3/blob/9cc9a875e636a1dcf36cc1e07bdf77e1ad6e2c74/src/layout/treemap.js>
  137. * with some modifications made for this program.
  138. * See the license statement at the head of this file.
  139. *
  140. * @protected
  141. * @param {module:echarts/data/Tree~TreeNode} node
  142. * @param {Object} options
  143. * @param {string} options.sort 'asc' or 'desc'
  144. * @param {number} options.squareRatio
  145. * @param {boolean} hideChildren
  146. * @param {number} depth
  147. */
  148. function squarify(node, options, hideChildren, depth) {
  149. var width;
  150. var height;
  151. if (node.isRemoved()) {
  152. return;
  153. }
  154. var thisLayout = node.getLayout();
  155. width = thisLayout.width;
  156. height = thisLayout.height; // Considering border and gap
  157. var nodeModel = node.getModel();
  158. var borderWidth = nodeModel.get(PATH_BORDER_WIDTH);
  159. var halfGapWidth = nodeModel.get(PATH_GAP_WIDTH) / 2;
  160. var upperLabelHeight = getUpperLabelHeight(nodeModel);
  161. var upperHeight = Math.max(borderWidth, upperLabelHeight);
  162. var layoutOffset = borderWidth - halfGapWidth;
  163. var layoutOffsetUpper = upperHeight - halfGapWidth;
  164. node.setLayout({
  165. borderWidth: borderWidth,
  166. upperHeight: upperHeight,
  167. upperLabelHeight: upperLabelHeight
  168. }, true);
  169. width = mathMax(width - 2 * layoutOffset, 0);
  170. height = mathMax(height - layoutOffset - layoutOffsetUpper, 0);
  171. var totalArea = width * height;
  172. var viewChildren = initChildren(node, nodeModel, totalArea, options, hideChildren, depth);
  173. if (!viewChildren.length) {
  174. return;
  175. }
  176. var rect = {
  177. x: layoutOffset,
  178. y: layoutOffsetUpper,
  179. width: width,
  180. height: height
  181. };
  182. var rowFixedLength = mathMin(width, height);
  183. var best = Infinity; // the best row score so far
  184. var row = [];
  185. row.area = 0;
  186. for (var i = 0, len = viewChildren.length; i < len;) {
  187. var child = viewChildren[i];
  188. row.push(child);
  189. row.area += child.getLayout().area;
  190. var score = worst(row, rowFixedLength, options.squareRatio); // continue with this orientation
  191. if (score <= best) {
  192. i++;
  193. best = score;
  194. } // abort, and try a different orientation
  195. else {
  196. row.area -= row.pop().getLayout().area;
  197. position(row, rowFixedLength, rect, halfGapWidth, false);
  198. rowFixedLength = mathMin(rect.width, rect.height);
  199. row.length = row.area = 0;
  200. best = Infinity;
  201. }
  202. }
  203. if (row.length) {
  204. position(row, rowFixedLength, rect, halfGapWidth, true);
  205. }
  206. if (!hideChildren) {
  207. var childrenVisibleMin = nodeModel.get('childrenVisibleMin');
  208. if (childrenVisibleMin != null && totalArea < childrenVisibleMin) {
  209. hideChildren = true;
  210. }
  211. }
  212. for (var i = 0, len = viewChildren.length; i < len; i++) {
  213. squarify(viewChildren[i], options, hideChildren, depth + 1);
  214. }
  215. }
  216. /**
  217. * Set area to each child, and calculate data extent for visual coding.
  218. */
  219. function initChildren(node, nodeModel, totalArea, options, hideChildren, depth) {
  220. var viewChildren = node.children || [];
  221. var orderBy = options.sort;
  222. orderBy !== 'asc' && orderBy !== 'desc' && (orderBy = null);
  223. var overLeafDepth = options.leafDepth != null && options.leafDepth <= depth; // leafDepth has higher priority.
  224. if (hideChildren && !overLeafDepth) {
  225. return node.viewChildren = [];
  226. } // Sort children, order by desc.
  227. viewChildren = zrUtil.filter(viewChildren, function (child) {
  228. return !child.isRemoved();
  229. });
  230. sort(viewChildren, orderBy);
  231. var info = statistic(nodeModel, viewChildren, orderBy);
  232. if (info.sum === 0) {
  233. return node.viewChildren = [];
  234. }
  235. info.sum = filterByThreshold(nodeModel, totalArea, info.sum, orderBy, viewChildren);
  236. if (info.sum === 0) {
  237. return node.viewChildren = [];
  238. } // Set area to each child.
  239. for (var i = 0, len = viewChildren.length; i < len; i++) {
  240. var area = viewChildren[i].getValue() / info.sum * totalArea; // Do not use setLayout({...}, true), because it is needed to clear last layout.
  241. viewChildren[i].setLayout({
  242. area: area
  243. });
  244. }
  245. if (overLeafDepth) {
  246. viewChildren.length && node.setLayout({
  247. isLeafRoot: true
  248. }, true);
  249. viewChildren.length = 0;
  250. }
  251. node.viewChildren = viewChildren;
  252. node.setLayout({
  253. dataExtent: info.dataExtent
  254. }, true);
  255. return viewChildren;
  256. }
  257. /**
  258. * Consider 'visibleMin'. Modify viewChildren and get new sum.
  259. */
  260. function filterByThreshold(nodeModel, totalArea, sum, orderBy, orderedChildren) {
  261. // visibleMin is not supported yet when no option.sort.
  262. if (!orderBy) {
  263. return sum;
  264. }
  265. var visibleMin = nodeModel.get('visibleMin');
  266. var len = orderedChildren.length;
  267. var deletePoint = len; // Always travel from little value to big value.
  268. for (var i = len - 1; i >= 0; i--) {
  269. var value = orderedChildren[orderBy === 'asc' ? len - i - 1 : i].getValue();
  270. if (value / sum * totalArea < visibleMin) {
  271. deletePoint = i;
  272. sum -= value;
  273. }
  274. }
  275. orderBy === 'asc' ? orderedChildren.splice(0, len - deletePoint) : orderedChildren.splice(deletePoint, len - deletePoint);
  276. return sum;
  277. }
  278. /**
  279. * Sort
  280. */
  281. function sort(viewChildren, orderBy) {
  282. if (orderBy) {
  283. viewChildren.sort(function (a, b) {
  284. var diff = orderBy === 'asc' ? a.getValue() - b.getValue() : b.getValue() - a.getValue();
  285. return diff === 0 ? orderBy === 'asc' ? a.dataIndex - b.dataIndex : b.dataIndex - a.dataIndex : diff;
  286. });
  287. }
  288. return viewChildren;
  289. }
  290. /**
  291. * Statistic
  292. */
  293. function statistic(nodeModel, children, orderBy) {
  294. // Calculate sum.
  295. var sum = 0;
  296. for (var i = 0, len = children.length; i < len; i++) {
  297. sum += children[i].getValue();
  298. } // Statistic data extent for latter visual coding.
  299. // Notice: data extent should be calculate based on raw children
  300. // but not filtered view children, otherwise visual mapping will not
  301. // be stable when zoom (where children is filtered by visibleMin).
  302. var dimension = nodeModel.get('visualDimension');
  303. var dataExtent; // The same as area dimension.
  304. if (!children || !children.length) {
  305. dataExtent = [NaN, NaN];
  306. } else if (dimension === 'value' && orderBy) {
  307. dataExtent = [children[children.length - 1].getValue(), children[0].getValue()];
  308. orderBy === 'asc' && dataExtent.reverse();
  309. } // Other dimension.
  310. else {
  311. dataExtent = [Infinity, -Infinity];
  312. each(children, function (child) {
  313. var value = child.getValue(dimension);
  314. value < dataExtent[0] && (dataExtent[0] = value);
  315. value > dataExtent[1] && (dataExtent[1] = value);
  316. });
  317. }
  318. return {
  319. sum: sum,
  320. dataExtent: dataExtent
  321. };
  322. }
  323. /**
  324. * Computes the score for the specified row,
  325. * as the worst aspect ratio.
  326. */
  327. function worst(row, rowFixedLength, ratio) {
  328. var areaMax = 0;
  329. var areaMin = Infinity;
  330. for (var i = 0, area = void 0, len = row.length; i < len; i++) {
  331. area = row[i].getLayout().area;
  332. if (area) {
  333. area < areaMin && (areaMin = area);
  334. area > areaMax && (areaMax = area);
  335. }
  336. }
  337. var squareArea = row.area * row.area;
  338. var f = rowFixedLength * rowFixedLength * ratio;
  339. return squareArea ? mathMax(f * areaMax / squareArea, squareArea / (f * areaMin)) : Infinity;
  340. }
  341. /**
  342. * Positions the specified row of nodes. Modifies `rect`.
  343. */
  344. function position(row, rowFixedLength, rect, halfGapWidth, flush) {
  345. // When rowFixedLength === rect.width,
  346. // it is horizontal subdivision,
  347. // rowFixedLength is the width of the subdivision,
  348. // rowOtherLength is the height of the subdivision,
  349. // and nodes will be positioned from left to right.
  350. // wh[idx0WhenH] means: when horizontal,
  351. // wh[idx0WhenH] => wh[0] => 'width'.
  352. // xy[idx1WhenH] => xy[1] => 'y'.
  353. var idx0WhenH = rowFixedLength === rect.width ? 0 : 1;
  354. var idx1WhenH = 1 - idx0WhenH;
  355. var xy = ['x', 'y'];
  356. var wh = ['width', 'height'];
  357. var last = rect[xy[idx0WhenH]];
  358. var rowOtherLength = rowFixedLength ? row.area / rowFixedLength : 0;
  359. if (flush || rowOtherLength > rect[wh[idx1WhenH]]) {
  360. rowOtherLength = rect[wh[idx1WhenH]]; // over+underflow
  361. }
  362. for (var i = 0, rowLen = row.length; i < rowLen; i++) {
  363. var node = row[i];
  364. var nodeLayout = {};
  365. var step = rowOtherLength ? node.getLayout().area / rowOtherLength : 0;
  366. var wh1 = nodeLayout[wh[idx1WhenH]] = mathMax(rowOtherLength - 2 * halfGapWidth, 0); // We use Math.max/min to avoid negative width/height when considering gap width.
  367. var remain = rect[xy[idx0WhenH]] + rect[wh[idx0WhenH]] - last;
  368. var modWH = i === rowLen - 1 || remain < step ? remain : step;
  369. var wh0 = nodeLayout[wh[idx0WhenH]] = mathMax(modWH - 2 * halfGapWidth, 0);
  370. nodeLayout[xy[idx1WhenH]] = rect[xy[idx1WhenH]] + mathMin(halfGapWidth, wh1 / 2);
  371. nodeLayout[xy[idx0WhenH]] = last + mathMin(halfGapWidth, wh0 / 2);
  372. last += modWH;
  373. node.setLayout(nodeLayout, true);
  374. }
  375. rect[xy[idx1WhenH]] += rowOtherLength;
  376. rect[wh[idx1WhenH]] -= rowOtherLength;
  377. } // Return [containerWidth, containerHeight] as default.
  378. function estimateRootSize(seriesModel, targetInfo, viewRoot, containerWidth, containerHeight) {
  379. // If targetInfo.node exists, we zoom to the node,
  380. // so estimate whole width and height by target node.
  381. var currNode = (targetInfo || {}).node;
  382. var defaultSize = [containerWidth, containerHeight];
  383. if (!currNode || currNode === viewRoot) {
  384. return defaultSize;
  385. }
  386. var parent;
  387. var viewArea = containerWidth * containerHeight;
  388. var area = viewArea * seriesModel.option.zoomToNodeRatio;
  389. while (parent = currNode.parentNode) {
  390. // jshint ignore:line
  391. var sum = 0;
  392. var siblings = parent.children;
  393. for (var i = 0, len = siblings.length; i < len; i++) {
  394. sum += siblings[i].getValue();
  395. }
  396. var currNodeValue = currNode.getValue();
  397. if (currNodeValue === 0) {
  398. return defaultSize;
  399. }
  400. area *= sum / currNodeValue; // Considering border, suppose aspect ratio is 1.
  401. var parentModel = parent.getModel();
  402. var borderWidth = parentModel.get(PATH_BORDER_WIDTH);
  403. var upperHeight = Math.max(borderWidth, getUpperLabelHeight(parentModel));
  404. area += 4 * borderWidth * borderWidth + (3 * borderWidth + upperHeight) * Math.pow(area, 0.5);
  405. area > MAX_SAFE_INTEGER && (area = MAX_SAFE_INTEGER);
  406. currNode = parent;
  407. }
  408. area < viewArea && (area = viewArea);
  409. var scale = Math.pow(area / viewArea, 0.5);
  410. return [containerWidth * scale, containerHeight * scale];
  411. } // Root position based on coord of containerGroup
  412. function calculateRootPosition(layoutInfo, rootRect, targetInfo) {
  413. if (rootRect) {
  414. return {
  415. x: rootRect.x,
  416. y: rootRect.y
  417. };
  418. }
  419. var defaultPosition = {
  420. x: 0,
  421. y: 0
  422. };
  423. if (!targetInfo) {
  424. return defaultPosition;
  425. } // If targetInfo is fetched by 'retrieveTargetInfo',
  426. // old tree and new tree are the same tree,
  427. // so the node still exists and we can visit it.
  428. var targetNode = targetInfo.node;
  429. var layout = targetNode.getLayout();
  430. if (!layout) {
  431. return defaultPosition;
  432. } // Transform coord from local to container.
  433. var targetCenter = [layout.width / 2, layout.height / 2];
  434. var node = targetNode;
  435. while (node) {
  436. var nodeLayout = node.getLayout();
  437. targetCenter[0] += nodeLayout.x;
  438. targetCenter[1] += nodeLayout.y;
  439. node = node.parentNode;
  440. }
  441. return {
  442. x: layoutInfo.width / 2 - targetCenter[0],
  443. y: layoutInfo.height / 2 - targetCenter[1]
  444. };
  445. } // Mark nodes visible for prunning when visual coding and rendering.
  446. // Prunning depends on layout and root position, so we have to do it after layout.
  447. function prunning(node, clipRect, viewAbovePath, viewRoot, depth) {
  448. var nodeLayout = node.getLayout();
  449. var nodeInViewAbovePath = viewAbovePath[depth];
  450. var isAboveViewRoot = nodeInViewAbovePath && nodeInViewAbovePath === node;
  451. if (nodeInViewAbovePath && !isAboveViewRoot || depth === viewAbovePath.length && node !== viewRoot) {
  452. return;
  453. }
  454. node.setLayout({
  455. // isInView means: viewRoot sub tree + viewAbovePath
  456. isInView: true,
  457. // invisible only means: outside view clip so that the node can not
  458. // see but still layout for animation preparation but not render.
  459. invisible: !isAboveViewRoot && !clipRect.intersect(nodeLayout),
  460. isAboveViewRoot: isAboveViewRoot
  461. }, true); // Transform to child coordinate.
  462. var childClipRect = new BoundingRect(clipRect.x - nodeLayout.x, clipRect.y - nodeLayout.y, clipRect.width, clipRect.height);
  463. each(node.viewChildren || [], function (child) {
  464. prunning(child, childClipRect, viewAbovePath, viewRoot, depth + 1);
  465. });
  466. }
  467. function getUpperLabelHeight(model) {
  468. return model.get(PATH_UPPER_LABEL_SHOW) ? model.get(PATH_UPPER_LABEL_HEIGHT) : 0;
  469. }