partition.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import { assign, isArray, reduce, size } from '@antv/util';
  2. import * as d3Hierarchy from 'd3-hierarchy';
  3. import { getAllNodes, getField } from './util';
  4. var DEFAULT_OPTIONS = {
  5. field: 'value',
  6. size: [1, 1],
  7. round: false,
  8. padding: 0,
  9. // 默认降序
  10. sort: function (a, b) { return b.value - a.value; },
  11. as: ['x', 'y'],
  12. // 是否忽略 parentValue, 当设置为 true 时,父节点的权重由子元素决定
  13. ignoreParentValue: true,
  14. };
  15. export function partition(data, options) {
  16. options = assign({}, DEFAULT_OPTIONS, options);
  17. var as = options.as;
  18. if (!isArray(as) || as.length !== 2) {
  19. throw new TypeError('Invalid as: it must be an array with 2 strings (e.g. [ "x", "y" ])!');
  20. }
  21. var field;
  22. try {
  23. field = getField(options);
  24. }
  25. catch (e) {
  26. console.warn(e);
  27. }
  28. var partition = function (data) {
  29. return d3Hierarchy.partition().size(options.size).round(options.round).padding(options.padding)(
  30. /**
  31. * d3Hierarchy 布局中需指定 sum 函数计算 node 值,规则是:从当前 node 开始以 post-order traversal 的次序为当前节点以及每个后代节点调用指定的 value 函数,并返回当前 node。
  32. * for example:
  33. * { node: 'parent', value: 10, children: [{node: 'child1', value: 5}, {node: 'child2', value: 5}, ]}
  34. * parent 所得的计算值是 sum(node(parent)) + sum(node(child1)) + sum(node(child2))
  35. * sum 函数中,d 为用户传入的 data, children 为保留字段
  36. */
  37. d3Hierarchy
  38. .hierarchy(data)
  39. .sum(function (d) {
  40. return size(d.children)
  41. ? options.ignoreParentValue
  42. ? 0
  43. : d[field] - reduce(d.children, function (a, b) { return a + b[field]; }, 0)
  44. : d[field];
  45. })
  46. .sort(options.sort));
  47. };
  48. var root = partition(data);
  49. /*
  50. * points:
  51. * 3 2
  52. * 0 1
  53. */
  54. var x = as[0];
  55. var y = as[1];
  56. root.each(function (node) {
  57. var _a, _b;
  58. node[x] = [node.x0, node.x1, node.x1, node.x0];
  59. node[y] = [node.y1, node.y1, node.y0, node.y0];
  60. // 旭日图兼容下 旧版本
  61. node.name = node.name || ((_a = node.data) === null || _a === void 0 ? void 0 : _a.name) || ((_b = node.data) === null || _b === void 0 ? void 0 : _b.label);
  62. node.data.name = node.name;
  63. ['x0', 'x1', 'y0', 'y1'].forEach(function (prop) {
  64. if (as.indexOf(prop) === -1) {
  65. delete node[prop];
  66. }
  67. });
  68. });
  69. return getAllNodes(root);
  70. }
  71. //# sourceMappingURL=partition.js.map