layout.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import { assign, isFunction, isString } from '@antv/util';
  2. import { center, justify, left, right, sankey } from './sankey';
  3. var ALIGN_METHOD = {
  4. left: left,
  5. right: right,
  6. center: center,
  7. justify: justify,
  8. };
  9. /**
  10. * 默认值
  11. */
  12. var DEFAULT_OPTIONS = {
  13. nodeId: function (node) { return node.index; },
  14. nodeAlign: 'justify',
  15. nodeWidth: 0.008,
  16. nodePadding: 0.03,
  17. nodeSort: undefined,
  18. };
  19. /**
  20. * 获得 align function
  21. * @param nodeAlign
  22. * @param nodeDepth
  23. */
  24. export function getNodeAlignFunction(nodeAlign) {
  25. var func = isString(nodeAlign) ? ALIGN_METHOD[nodeAlign] : isFunction(nodeAlign) ? nodeAlign : null;
  26. return func || justify;
  27. }
  28. export function getDefaultOptions(sankeyLayoutOptions) {
  29. return assign({}, DEFAULT_OPTIONS, sankeyLayoutOptions);
  30. }
  31. /**
  32. * 桑基图利用数据进行布局的函数,最终返回节点、边的位置(0 - 1 的信息)
  33. * 将会修改 data 数据
  34. * @param sankeyLayoutOptions
  35. * @param data
  36. */
  37. export function sankeyLayout(sankeyLayoutOptions, data) {
  38. var options = getDefaultOptions(sankeyLayoutOptions);
  39. var nodeId = options.nodeId, nodeSort = options.nodeSort, nodeAlign = options.nodeAlign, nodeWidth = options.nodeWidth, nodePadding = options.nodePadding, nodeDepth = options.nodeDepth;
  40. var sankeyProcessor = sankey()
  41. // .links((d: any) => d.links)
  42. // .nodes((d: any) => d.nodes)
  43. .nodeSort(nodeSort)
  44. .nodeWidth(nodeWidth)
  45. .nodePadding(nodePadding)
  46. .nodeDepth(nodeDepth)
  47. .nodeAlign(getNodeAlignFunction(nodeAlign))
  48. .extent([
  49. [0, 0],
  50. [1, 1],
  51. ])
  52. .nodeId(nodeId);
  53. // 进行桑基图布局处理
  54. var layoutData = sankeyProcessor(data);
  55. // post process (x, y), etc.
  56. var nodes = layoutData.nodes
  57. .map(function (node) {
  58. var x0 = node.x0, x1 = node.x1, y0 = node.y0, y1 = node.y1;
  59. /* points
  60. * 3---2
  61. * | |
  62. * 0---1
  63. */
  64. node.x = [x0, x1, x1, x0];
  65. node.y = [y0, y0, y1, y1];
  66. return node;
  67. })
  68. .filter(function (node) {
  69. return node.name !== null;
  70. });
  71. var links = layoutData.links
  72. .map(function (edge) {
  73. var source = edge.source, target = edge.target;
  74. var sx = source.x1;
  75. var tx = target.x0;
  76. edge.x = [sx, sx, tx, tx];
  77. var offset = edge.width / 2;
  78. edge.y = [edge.y0 + offset, edge.y0 - offset, edge.y1 + offset, edge.y1 - offset];
  79. return edge;
  80. })
  81. .filter(function (edge) {
  82. var source = edge.source, target = edge.target;
  83. return source.name !== null && target.name !== null;
  84. });
  85. return { nodes: nodes, links: links };
  86. }
  87. //# sourceMappingURL=layout.js.map