treemapLayout.js 18 KB

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