partition.js 2.8 KB

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