treemapLayout.js 18 KB

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